Issue with Axios Interceptor not correctly applying token from local storage on initial request

Having an issue with my Vue application where the axios intercept is not applying the authorization token as expected.

axios.interceptors.request.use(config => {
  let token = localStorage.getItem("jwt_token")
  console.log("Token is: ", token)
  console.log(typeof token)
  if (token) {
    axios.defaults.headers.Authorization = `Bearer ${token}`
    }
  console.log(config)
  return config
});

After logging the Token before setting it to the Auth header, I noticed an issue in my console log output.

The first request shows the token correctly in the log, but somehow it's set as null inside the header leading to a 422 response.

Interestingly, on the second API request, the token applies properly and data is successfully retrieved.

Answer №1

Once the config object reaches your interceptor, it has already been combined with the default settings. This means that setting the token to

axios.defaults.headers.Authorization
will not impact the current request's configuration.

Therefore, all you need in your interceptor is...

config => {
  let token = localStorage.getItem("jwt_token")
  config.headers = Object.assign({
    Authorization: `Bearer ${token}`
  }, config.headers)
  return config
}

In this solution, I have utilized Object.assign() to ensure that the current headers are added last and do not overwrite any existing Authorization header.

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

Deploy a Node.js websocket application on Azure Cloud platform

After smoothly running on Heroku, the server app encountered a problem with startup after moving to Azure. Below is the code snippet: const PORT = process.env.PORT || 2498; const INDEX = '/index.html'; const server = express() .use((req, res ...

Increasing counter on the backend using PHP or JavaScript

Having done my research, I am struggling to find a suitable solution for my project. I need a server-side incremental counter that resets daily. The goal is for every website visitor to see the same number on the counter. Is there a PHP script or JavaScr ...

Determine the maximum and minimum numbers by inputting a number and utilizing jQuery

<script type="text/javascript"> function findLargestNumber() { var number1, number2; number1 = Number(document.getElementById("N").value); number2 = Number(document.getElementById("M").value); if (number1 > numb ...

Issue with Angular 13 Bootstrap5 Navbar's functionality

Angular 13 is my framework of choice, and I recently integrated Bootstrap 5 into my project using the command below: ng add @ng-bootstrap/ng-bootstrap As for the index.js file content, it looks like this: <!doctype html> <html lang="en" ...

Blank Vue Page Generated by Laravel Mix

While attempting to run npm run dev or npm run production, I encountered an error stating that the Vue file did not have loaders defined. To resolve this issue, I turned to this helpful resource: Compillation problem of extensions in vuejs I made use o ...

Error 500 occurs during an ajax call to the server, however, the call works fine when running on localhost

I encountered an issue with my JavaScript code when making an AJAX call to a specific server. The strange thing is that it works perfectly fine when I use localhost, but as soon as I try calling the service from the uploaded server, I get an ERROR 500. T ...

Empty files following XML retrieval using node.js

Currently, I am using the below code snippet to retrieve Yahoo weather XML files: // This script needs request libraries. // npm install request var fs = require('fs'); var woeid_array = fs.readFileSync('woeid.txt').toString().split(" ...

Utilizing jQuery's scaling function allows for exponential growth in size

Currently, I have a function implemented that scales up pictures on mouse-enter and returns them to normal size on mouse-out. However, there is an issue where if I quickly move the mouse out and then back in before the picture has returned to its origina ...

JavaScript timekeepers and Ajax polling/scheduling

After looking into various methods like Comet and Long-Polling, I'm searching for a simpler way to push basic ajax updates to the browser. I've come across the idea of using Javascript timers to make Ajax calls at specific intervals. Is this app ...

What is the reason for `then` generating a new promise rather than simply returning the promise that was returned by `

I've been curious about why, in a situation where the onFulfilled handler of then() returns a promise p2, then() creates a new promise p3 instead of simply returning p2? For example: let p1 = new Promise(function(resolve, reject) { resolve(42); ...

When I modify the state in Vue.js, the two-way binding feature does not seem to function properly

I'm facing an issue with my dynamic array "slots" of objects which looks something like this: [{"availability": 1},{"availability": 3}] I render multiple inputs in Vue.js using v-for like so: <div v-for="slot in array"><input v-model="slot.av ...

What causes immediately invoked functions within event handlers to be executed before the event is triggered?

let b = (function maria() { alert("ee"); })(); * this code runs as soon as the page loads * <button onclick="b">Click me</button> * this code only runs when button is clicked * <button onclick="alert('ee')">Click m ...

Error: The data in the JSON array is not defined

I have an example of JSON array data: var arr= [ { "id": 1, "organizationName": "psda", "Number": "12345" }, { "id": 2, "organizationNameEN": "psda", "Number": "123456" } ] After retrieving ...

Steps to display all Vue files in test coverage using Vue-cli 3 and Jest

I'm hitting a snag while attempting to set up Vue CLI 3 with Jest for displaying test coverage. Despite my best efforts, the coverage report still shows zero coverage: Ran all test suites. ----------|----------|----------|----------|----------|------ ...

Acquire user input using AngularJS

Is it possible to retrieve the value of an input text using AngularJS without utilizing a Controller? If so, what approach would achieve this? I have come across some resources discussing similar queries, but they all involve .controller here is one such ...

Express.js throws an error of type TypeError when attempting to set a property 'session' on an undefined object

Encountering this issue when attempting to start my express server with node server.js, and I'm struggling to identify the root cause. Despite updating my app with express 4.0, I can't seem to pinpoint the error. Can anyone assist in identifying ...

Dealing with textarea in Javascript

I am new to JavaScript and facing a challenge in creating a delimited string from a textarea input. The issue is that when the textarea is passed in, it includes newlines for each row. I aim to parse the entire textarea content into a string with a delimit ...

The initial axios GET request fails to retrieve data upon the first click

Having trouble retrieving data with button click. The issue is that the data is not fetched when clicking the button for the first time, but works fine on the second click. Here's the code snippet: const learnMores = document.querySelectorAll('. ...

Steps to prevent flickering when loading an Iframe

Here is the code for my Iframe: <iframe id="iframe1" frameborder="0" style=" width: 379px; height:110%;" src="frmChatRequest.aspx" scrolling="no" runat="server"> </iframe> Within the frmChatRequest.aspx page (seen in the Iframe), I ha ...

Angular 2 ngFor generates a collection of rows and columns forming a single large column

It seems that ngfor is generating divs one by one, resulting in a poor design where they are stacked on top of each other. I would like to achieve a layout like this: [1] [2] [3] [4] [5] [6] However, the current outcome looks like this: [ 1 ] [ 2 ] [ 3 ...