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

Validation of Regular Expressions in Javascript

I am trying to implement control validation using Javascript. The validation criteria states that the number should consist of a maximum of 12 digits, with the first 7 being '9900000' followed by either a '0' or a '1', and en ...

Alter the component and then refresh it

I am encountering an issue with a component that has an event handler for a "like" icon. The goal is to allow users to click the like icon, update the database to indicate their liking of the item, and then re-render the component to visually reflect this ...

Is there a way to utilize regular expressions in React to dynamically insert onclick events into specific words within a text block?

I've been experimenting with regular expressions in React to implement an onclick event for each word in a text. I've attempted two different strategies, but neither has been successful thus far. Initially, I tried: return( <div> & ...

Custom Typescript type that runs concurrently with the base type is disregarded

Assumption: When creating a custom type that mirrors an existing type, the expectation is for variables assigned to that type to maintain it and not default back to the base type. In the function f provided below, the expected return type should be Dog ins ...

Dynamic JavaScript animation to retrieve the position of an element on-the-fly

I am currently exploring the world of animation in JavaScript and I have a few practical questions. In my script, I am attempting to "launch" a "rocket" upon clicking a "button". What I've observed is that although my function calculates values as int ...

Using perl ajax to modify a table

In my current Perl script, I am working on a functionality where I retrieve data from an xls file and display it as input text on a webpage. The objective is that when a user selects the edit option from a menu, the entire table fetched from the xls file w ...

Mastering the utilization of the Data object in VueJS with Decorators can be tricky. One common error message you might encounter is, "Class method 'data' expected 'this' to be used."

Error > The class method 'data' should use 'this' but it is not. I encountered this issue and believed I fixed it as shown below: TypeScript Unexpected token, A constructor, method, accessor or property was expected <script lang ...

Keeping extensive files/information on disk in order to alleviate browser memory usage in JavaScript

Currently, I am faced with a challenge involving the encryption of very large files. Unfortunately, my browser keeps crashing due to running out of memory while trying to handle these massive files. To address this issue, I am considering transferring som ...

Understanding eventBus value listening in Vue.jsWould you like to learn how to

I've encountered an issue while trying to retrieve the search input value. Below is how I'm sending values using the event bus: import eventBus from "../../../services/eventBus"; export default { name: "Navbar", data() { return ...

Add a CSS class to the text that is selected within a Content Editable div

Hey there, I'm having an issue where the class is being applied to the button when pressed instead of the selected text. Here's my current code: The button needs to be a div, but it might be causing the problem. I just want the highlighted text ...

Create a duplicate of the information stored within the $scope variable

Suppose there are multiple variables stored in a $scope and the objective is to create a new object that only includes those variables, excluding all the internal Angular-related data. The specific names of the $scope variables may not be known. This can ...

Divide HTML elements every two words

Can you use CSS to break up HTML content after every 2 words, ensuring it works for any word combination? Example: // Original HTML content The cat is sleeping // Desired result: The cat is sleeping ...

"Challenges encountered when integrating Vue.js with Ngin

Hello, I'm currently running a setup with node, express, and vue. Below is my nginx configuration: server { listen 443; server_name mydomain.me; ssl on; ssl_certificate /root/mydomain.me.cert; ssl_certificate_key /ro ...

Connecting the value of one input to influence another input

There are two input boxes provided - one for current address and another for permanent address. When the checkbox is clicked, the value of the current address should be displayed in the permanent address box. However, I am facing an issue where when I unc ...

Solution for fixing the error: MongooseError [OverwriteModelError]: It is not possible to overwrite the `User` model after it has been compiled in

I am new to working with the MERN stack and currently attempting to create an exercise tracker app following a tutorial on YouTube. However, I am encountering the Mongoose: OverwriteModelError when running the server and cannot seem to identify where I am ...

There seems to be an issue with React-hook-form and material-ui not retaining value changes in the onBlur() method

Stepping into the realm of react-hook-form is a new experience for me. I'm putting in effort to grasp everything, but there are still some pieces missing from the puzzle. Seeking assistance akin to Obiwan Kenobi! The Dilemma at Hand: An <Textfiel ...

Problem with Cordova Android build

Currently, I am utilizing vue-cordova to incorporate cordova into my Vue.js framework. After successfully adding the android platform and generating the APK file, a new challenge arose. Despite days of development work, running cordova build android only ...

Appium with Node.js (wd) becomes unresponsive when unable to locate element

Encountering an issue while using appium with nodejs (wd) and mocha, as there is a loading view in the android app (blackbox testing & I'm not the developer) that needs to be waited for its disappearance. Attempted the following solution: wd.addPromi ...

Dimension of the element that has been positioned absolutely

One of my challenges involves working with an absolutely positioned div element (.tooltip) containing another div (.text) that has text with a set max-width. The issue arises when the left property of .tooltip is too large, causing its width to shrink du ...

Error retrieving Facebook access token using Node.js https.get()

I've been working on setting up a Facebook login flow in my node.js app, but I'm facing an issue where the access token isn't returning from the Facebook API when using node's https.get() method. Interestingly, I am able to retrieve the ...