Encountering 401 unauthorized error in Laravel Passport, Vue.js, and Axios integration

I am fairly new to VueJS and I am trying to retrieve data from a Laravel (passport) API. To do this, I have used npm i axios for making API requests. Below is the script code from my App.vue file:

import axios from 'axios';
export default {
  data () {
    return {
    }
  },
  created() {
    const postData = {
      grant_type: "password",
      client_id: 2,
      client_secret: 'MvEyvm3MMr0VJ5BlrJyzoKzsjmrVpAXp9FxJHsau',
      username: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e98490c48c84888085a98e84888085c78a8684">[email protected]</a>',
      password: '********',
      scope: ''
    }
    axios.post('http://localhost/api/oauth/token', postData)
    .then(response => {
      console.log(response.data.access_token);
      const header = {
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + response.data.access_token,
      };
      axios.get('http://localhost/api/api/user', {headers: header})
      .then(response => {
        console.log(response)
      })
    })
  }
}

The API.PHP (routes file for API):

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Also, here is the Middleware code used for fixing CORS in Laravel:

public function handle($request, Closure $next)
{
    $domains = ["http://localhost:8080"];

    if (isset($request->server()['HTTP_ORIGIN'])) {
        $origin = $request->server()['HTTP_ORIGIN'];
        if (in_array($origin, $domains)) {
            header('Access-Control-Allow-Origin: ' . $origin);
            header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization');
        }
    }

    return $next($request);
}

Despite seeing the token logged in the console with

console.log(response.data.access_token)
, I encounter a 401 unauthorized error with the subsequent request. I have tried various solutions without success. Any advice or suggestions would be greatly appreciated.

Answer №1

To ensure authenticity, the token must be included in the header of the Axios request so that the backend can verify it. This step should only be taken after confirming the proper functioning of the backend using Postman. To set the Axios header accordingly, use the following code snippet:

axios.defaults.baseURL = '/api'; axios.defaults.headers.common['Authorization'] = "Bearer " + your_token_variable

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create an interactive mechanism where one scrollbar dynamically adjusts another scrollbar and vice versa

Using the provided js-bin, how can I synchronize scrolling between the "left" div and the "right" div when using the mouse wheel? Currently, if you uncomment the code block, the scrolling behavior changes from scrolling by 100px per scroll to scrolling pi ...

Challenges in establishing the initial connection between Express.js and MongoDB

Having spent a significant amount of time researching how to set up MongoDb in an Express/NodeJs application, I believed I had a good understanding of how to implement it efficiently. I decided to initialize my mongodbConnection in the WWW file provided by ...

The child module invokes a function within the parent module and retrieves a result

Guardian XML <tr [onSumWeights]="sumWeights" > Algorithm sumWeights(): number { return // Calculate total value of all weights } Offspring @Input() onTotalWeights: () => number; canMakeChanges() { return this.onTota ...

Tips for displaying a tooltip when hovering over a label in a Material UI slider

I'm currently working on a slider quiz and my goal is to have the tooltip appear when hovering over the label on the slider. Currently, I can only see the tooltip when I hover directly on the thumb at the location of my mouse. Refer to the image belo ...

Attempting to incorporate the jquery-mousewheel plugin into the jquery cycle2 library

I've been working on integrating the jquery-mousewheel plugin (https://github.com/jquery/jquery-mousewheel) with the jquery cycle2 plugin. Initially, everything was running smoothly until I encountered an issue where mouse scrolling was generating ex ...

Transferring information between an ASP web form page and an Angular2 application

Currently, I am working on a project that involves dealing with a legacy WebForms system. The system is gradually being updated to Angular 2, but the transition is happening incrementally. In order to effectively integrate information from the legacy sect ...

What is the best way to pass multiple parameters along with the context to a URL in Vuex?

Link to StackBlitz I am currently working on how to send multiple action parameters with context to a URL. I have been encountering a 400 error in my attempts. The selectedPoint and departurePoint are coming from child components and stored as variables i ...

Unable to run the command cd /var/www within the Docker container

Encountering an error message that says: /run.sh: 3: cd: can't cd to /var/www However, upon running an interactive shell, the current directory is confirmed to be /var/www. This dockerfile configuration is as follows: FROM php:8.1.0-fpm # Set worki ...

Exploring Vue Component Features through Conditional Display

I am working with a vue component called <PlanView/>. In my code, I am rendering this component conditionally: <div v-if="show_plan" id="mainplan"> <PlanView/> </div> <div class="icon" v-else> ...

What is the most effective way to extract the value of a "$3" element using Selenium in Python?

I am facing a challenge in fetching an element from the netlify dashboard. The code I have currently grabs the base element that the web developers have set, indicating that it gets updated with javascript. However, I am having trouble accessing this updat ...

Is there a way to set a value within a jQuery function, and then invoke another function to utilize that value?

Suppose I have a function called isPercentage, which utilizes a value that is defined within the function it's being called in: isPercentage = function(){ if (value < 1){ value = value * 100; console.log(value); ...

The Express router is failing to recognize the mongoose model

Currently, I am developing a node.js application and encountering an issue where I receive a reference error stating that Post is not defined every time I run this specific code. Interestingly, when I move the post route from submit.js to app.js, the code ...

Would you say the time complexity of this function is O(N) or O(N^2)?

I am currently analyzing the time complexity of a particular function. This function takes a string as input, reverses the order of words in the string, and then reverses the order of letters within each word. For example: “the sky is blue” => “eu ...

What is the best way to establish a default search query within the vue-multiselect component?

I have incorporated vue-multiselect into my project. You can find more information about it here. This is a snippet of my template structure: <multiselect v-model="value" :options="options" searchable="true"></multiselect> When I open the mu ...

Data structure designed specifically for a drawing tool application

Currently, I am in the process of developing a unique sketching application using the HTML5 Canvas element. Despite my progress, there is one particular challenge that has stumped me. The main concept of the application involves allowing users to manipula ...

Personalized JSON response type for AJAX requests

Do you think it's possible to achieve this? I have an idea to create a unique dataType called "json/rows". This new dataType would parse the server output text and manipulate it in some way before passing it to the success function. What do you think ...

The Vue/Nuxt application displays content duplication on each page, rendering the content twice without duplicating the components

I recently delved into Vue/Nuxt programming and worked through a tutorial on adding a blog, which I then customized for my website. Everything functions perfectly except that the content is rendering twice. It goes from rendering NavPage (component) > cont ...

Obtaining a Variable Element through Selector

When working with Puppeteer, I am faced with the challenge of clicking on a web button that has a dynamic id like: #product-6852370-Size. Typically, I would use the following code: page.click('#product-6852370-Size'); However, the number withi ...

Discover the basics of incorporating libraries using npm

As a beginner in JavaScript, I am looking to incorporate moment.js or another library into my project. However, I am unsure of how to properly set up my project so that I can import from the library. Here is how I have structured my HTML: <!DOCTYPE html ...

The JavaScript code is failing to retrieve the longitude and latitude of the location on a mobile browser

I am having an issue with my Javascript code not properly retrieving the longitude and latitude from the mobile Chrome browser. While this code works fine on laptop or desktop browsers, it seems to be failing on mobile devices: <script> if (nav ...