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

The Vuetify data-table header array is having trouble accepting empty child associations

My Vuetify data-table relies on a localAuthority prop from a rails backend. Everything runs smoothly until an empty child association (nested attribute) is passed, specifically 'county': <script> import axios from "axios"; exp ...

Switching between different CSS files based on the URL using jQuery or another method

Is it feasible to apply specific styles based on the ID or load various CSS files depending on the URL you are visiting? For example: <script> if(location.href == 'http://jpftest2.tumblr.com/about'){ document.write('<style type= ...

It appears that the $http request is causing an endless $digest Loop

Looking to determine a user's status in my AngularJS app in order to display specific functionality content, here is the HTML code in my view: <span ng-show="authService.isSuperUser()">You are a Super User</span> To check if the user has ...

What is the best way to transform this unfamiliar CSS element into JavaScript code?

I'm facing an issue where I want to animate a CSS image based on time constraints, but since it's in CSS, I'm unable to achieve the desired effect. The animation in question is not the sun itself, but rather a yellowish half-circle animation ...

Is it possible to iterate through HTML elements without relying on forEach()?

Currently working on my web-based system using Node.js and HTML. Are there any alternative ways to iterate through HTML elements without using forEach? I'm considering something like this (for example): <% for(var ctr=0; ctr<arrayname.length ...

Stop jQuery from submitting the form in case of validation errors

Hey there, I'm currently working on preventing the AJAX form submission function from happening if one of the inputs fails validation. Edit: Specifically, I'm looking for guidance on what changes need to be made in //Adult age validation and var ...

"Return to the top" feature that seamlessly integrates with jQuery's pop-up functionality

Currently, I am facing an issue with a jQuery selectmenu list that opens as a popup due to its length. My goal is to add a "back to top" button at the end of the list. While researching online, I came across this tutorial which seems promising, but unfor ...

Efficiently incorporating multiple properties into one in Angular

Within my Angular service, I have defined variables in the following manner: export class MyService { someVariableA = 1; someParams = { someVariableB, otherVariable: this.someVariableA }; } In a component, I update 'someVariableA&a ...

What is the best method for showcasing numerous dropdown lists using JavaScript along with conditional if-else statements?

Hello everyone, I am currently new to javascript and I'm attempting to build a small web application using javascript. However, I am facing an issue with printing the drop-down list output. Could someone please assist me in resolving this problem? < ...

What could be causing a case where this.props.posts is undefined in React and Redux

Recently, I attempted to follow a React and Redux tutorial on a blog. However, when working with the PostList component, I encountered an error related to the reducer binding. My main goal was simply to render the renderPost function by calling the reducer ...

pressing the downward arrow does not cause the number to decrease

I'm facing an issue with my code in this video. The increment is working when the upward arrow is clicked, but not the decrement. I suspect there's a problem with the jQuery code. Initially, I tried modifying from top to bottom, and changing +1 t ...

Transforming a form submission into an AJAX post while already in an AJAX post

I am looking to convert a form submission to an ajax post request while working within the codeigniter framework. The current JavaScript code is: $('#book-appointment-submit').click(function(event) { event.preventDefault(); var formData ...

A JavaScript code snippet that stores the total number of bytes read from a CSV file in a variable

I currently have a CSV file located on a web server that is regularly updated with numeric and string data of varying lengths. I am seeking a solution to calculate the total byte values of each row when reading the file, as the byte count is crucial due ...

The logout feature might refresh the page, yet the user remains logged in

Currently, I am enrolled in a course on Udemy where the instructor is utilizing Angular 2. My task involves building the app using the latest version of Angular. The issue that I am facing pertains to the logout functionality. After successfully logging ou ...

How can I send two responses in a single POST request using node.js?

Below is my router setup for handling responses: questionRouter.post('/questionsReply', (req, res) => { twilioResp(req, res); var newResponse = new Response(req.body); newResponse.save((err, data) => { if (err) return handleDBError(er ...

What is the reason behind being able to use any prop name in a React function without explicitly mentioning it?

Currently, I'm delving into the world of mobX-state-tree, and in the tutorial code that I'm exploring, there is an interesting piece that caught my eye. const App = observer(props => ( <div> <button onClick={e => props.store. ...

Upload an image converted to `toDataURL` to the server

I've been attempting to integrate the signature_pad library, found at signature_pad, but I am struggling to grasp its functionality. Can someone guide me on how to retrieve an image value and send it to my server? Edit: I have experimented with dec ...

What is the process for inserting a watermark onto an image as it is being retrieved from Firebase?

I am developing a React website where I need to implement a feature that adds a watermark to an image when it is retrieved from Firebase storage. Is there a way to apply a watermark while accessing the image from the storage? I have already looked into Ho ...

Challenges arise with CSS alignment when adding d3.js charts to a webpage

I'm puzzled by the empty space that appears between the left column (highlighted in the image) and the header. This peculiar gap only seems to occur when the middle column is filled with a chart. I've scrutinized the code using Chrome Developer t ...

React Sentry Error: Attempting to access properties of undefined object (reading 'componentStack')

Utilizing the ErrorBoundry component from Sentry in my react project has been a goal of mine. I aim to confine the errors reported to Sentry specifically for my React app, as it is deployed on multiple websites and I want to avoid picking up every JS error ...