I am receiving a 401 error when attempting to verify the token following a successful login

I've been working on a small project utilizing VueJS, Vue Router, and Laravel for the backend.

Despite several attempts, I haven't been successful in implementing navigation guards.

My login component is functioning properly. Here's my login method (which utilizes localStorage for storing token and other data):

Login.vue

login() {

      axios.post('http://proudata.test/api/login', this.user).then(response => {

        if (response.data.data.isLogged == true) {
          
          localStorage.setItem('token', JSON.stringify(response.data));

          router.push({ name: 'dashboard' });

        }

      }).catch(error => {
        this.error = true;
        this.message = error.response.data.message
      });

    }

The issue arises with the navigation guard, specifically in beforeEach. My goal is to verify the token validity each time a user navigates to another page:

This is my routes.js file :

router.beforeEach(async (routeTo, routeFrom, next) => {
 
  const authRequired = routeTo.matched.some((route) => route.meta.authRequired)
  
  if (!authRequired) return next()

    // **THE PROBLEM IS HERE IM GETTING 401 JUST AFTER LOGIN**
    await client.get('validate-token').then(() => {
      next();
    }).catch(() => {
      next({ name: 'login' })
    });
 
});

In addition, I have a separate axios client file that handles headers:

Client.js

import axios from 'axios';

let userData = localStorage.getItem('token');

let authenticated = {data:{}};

if(userData !== null){
    authenticated = JSON.parse(userData);
}

const client = axios.create({
    baseURL: ((authenticated.data.domain !== null) ? authenticated.data.domain : 'http://domain.test/api')
});

client.interceptors.request.use(config => {

    if(userData !== null){

        config.headers.Authorization = authenticated.data.token ? `Bearer ${authenticated.data.token}` : null; 
    }

    return config;

});

export default client;

After clicking the login button, I receive a response indicating successful login:

Server Response (201), logged successfully

{
   data:{
     isLogged:true,
     token: gkljdfslkgjdfklgjfdlkgj,
     domain: http://user.multitenancy.test
   }
} 

However, when attempting to validate the token, I encounter a 401 error suggesting that the token is not being sent as Bearer Authorization, despite being saved in localStorage. Any insights on why this may be happening?

Should I reconsider verifying the token in beforeEach? What could potentially be causing this issue?

Answer №1

Make sure to retrieve the token from localStorage each time you need fresh data.

Remember to also set the config.baseURL in your interceptor every time.

import axios from 'axios';

let userData = localStorage.getItem('token');

let authenticated = {data:{}};

if(userData !== null){
    authenticated = JSON.parse(userData);
}

const client = axios.create({
    baseURL: ((authenticated.data.domain !== null) ? authenticated.data.domain : 'http://domain.test/api')
});

client.interceptors.request.use(config => {
    // Get the token from localStorage each time for updated data
    let userData = localStorage.getItem('token');

    let authenticated = {data:{}};
    
    if(userData !== null){
        authenticated = JSON.parse(userData);
        config.headers.Authorization = authenticated.data.token ? `Bearer ${authenticated.data.token}` : null;
        config.baseURL = ((authenticated.data.domain !== null) ? authenticated.data.domain : 'http://domain.test/api')
    }

    return config;

});

export default client;

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

Issue with writing JSON data to a file in node.js

When I try to write JSON objects from the Twitter API to a file using the fs.appendFile method, all that gets written is "[object Object]". The JSON objects look fine when logged to the console, so I'm not sure why this is happening. For example, the ...

Add the text received from the Ajax request to an array specifically designed for AmCharts

Hello, I'm new to JavaScript and seeking assistance. My goal is to create a chart with real-time data from my MCU, but I'm unsure about pushing a string into an array. Currently, the Array (chart.dataProvider) in this code remains undefined. var ...

You can't send headers to the client in Express after they have already been set

I successfully registered and inserted a record in my MongoDB. However, I encountered an error when trying to log in at the line "!user && res.status(401).json("Wrong User Name");" Cannot set headers after they are sent to the client at new NodeError ...

JavaScript is claiming that my class method is invalid, despite the fact that it is obviously a valid function

Implementing a genetic algorithm using node has been my latest challenge. After browsing through the existing questions on this topic, I couldn't find anything relevant to my issue. The problem arises when I attempt to call the determine_fitness metho ...

Utilize dynamic function calls in JavaScript

I am trying to dynamically call a function from a string like "User.find". The goal is to call the find() function in the User object if it exists. This is what my attempt looks like: var User = {}; User.find = function(){ return 1; } var input ...

Error encountered when attempting to use the submit button in AngularJS

My goal is to create a simple Angular application that takes input of two numbers (n1 and n2) and then prints their sum. I have integrated Bootstrap for styling, but noticed that nothing was happening upon submission. To troubleshoot, I added an alert() fu ...

Server-side access to form data has been restricted

When I make a PUT request from the frontend, I am currently using the XMLHttpRequest and FormData API. However, on the server side, I am not receiving any data such as req.params, req.body, and req.query are all empty. Front-end Implementation var report ...

Is it achievable to modify the appearance of the "Saved Password" style on Firefox?

After creating a login page that initially had a certain aesthetic, I encountered an issue when saving login data in Firefox. The saved login page took on a yellow-ish tint that was not present in my original design: I am now seeking advice on how to remo ...

Utilizing LocalStorage in an Ionic application to store data on a $scope

Having trouble saving the array named $scope.tasks to LocalStorage while building a To Do List app. Tried multiple times but can't figure it out. Here's the code, appreciate any help :^) index.html <!DOCTYPE html> <html> <head& ...

Transferring a PHP array to JavaScript using AJAX

I have spent time searching for answers to my issue with no success. My PHP file includes the following array: $data = ['logged' => $_SESSION['loggedin'], 'sessName' => $_SESSION['name']]; echo json_encode($dat ...

Implementing Node Express 4 to efficiently handle response generation from successive API requests

I'm currently in the process of developing a NodeJS server using Express4. The main purpose of this server is to act as a mediator between my frontend Angular app and a 3rd party API. I've set up a specific path that my frontend app can request, ...

What is the syntax for using escape characters in Vue?

Looking to create a website similar to CodePen? I have developed a library of assets including buttons, cards, and effects, all built using vue.js. Each asset includes HTML, CSS, and sometimes JS code. In my vanilla JS version, I formatted the code using e ...

Utilizing jquery and ajax to showcase a series of images prior to uploading them

I have been attempting to create a feature that allows for the preview of multiple images before uploading them to my website. Unfortunately, it's not working as expected and I am unable to identify any errors in the console. Below is the JavaScript c ...

Analyzing file data while uploading the file

Does anyone have a solution for extracting the content from an uploaded file in express/nodejs without saving it as a temporary file? I have code that successfully pipes the input to a filestream, but I'm struggling to deserialize the upload to a pla ...

Can someone guide me on incorporating bluebird promises with request-extensible?

I'm interested in utilizing the bluebird library to create a promise-based asynchronous web client. Currently, I have been using the request-promise package for this purpose. To get started, I simply include the following lines of code at the beginnin ...

Utilizing getUserMedia to capture portrait shots with the back camera

I am encountering an issue with starting the back camera in portrait mode using navigator.mediaDevices.getUserMedia in React. The camera does not appear to be taking into account the constraints I have set. Below is how the code looks for initialization: ...

"Encountering a Dojo error where the store is either null or not recognized

I encountered an issue with the function I have defined for the menu item "delete" when right-clicking on any folder in the tree hierarchy to delete a folder. Upon clicking, I received the error message "Store is null or not an object error in dojo" Can s ...

When the mouse leaves, the gauge chart component's size will expand

I have encountered a problem while using the react-gauge-chart library in my react project. Within the project, I have integrated a popover component using material-ui and incorporated the gauge chart component from the library within the popover modal. T ...

Vue.js - The prop "src" is invalid as the type check has failed. The expected type should be either a string or an object, but a

I am currently working on integrating an image into my Firebase's Firestore and Storage, and then displaying it on a v-card component. Here is the code for my v-card: <v-row> <v-col cols="3" v-for="massage in massages" ...

How many times can vue.js v-for iterate through a variable?

Looking to loop through rows in a table using a range? Most examples show how to do this for a fixed value, like: <div> <span v-for="n in 10">{{ n }} </span> </di But what if you want to achieve this with a variable like below? &l ...