Global axios configuration containing an undefined bearer token

After creating a Vue app using Axios that was installed via Vue UI dependency installation, I encountered an issue with the post headers returning an undefined token Bearer undefined. To resolve this, I made changes to my main.js file. Initially, I had added a global configuration as follows:

import Vue from "vue";
import "./plugins/vuetify";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import axios from "axios";

Vue.config.productionTip = false;

axios.defaults.baseURL = "http://localhost:3000";
axios.defaults.headers.common["Authorization"] = `Bearer ${localStorage.token}`;
axios.defaults.headers.post["Content-Type"] = "application/json";

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

However, this setup resulted in the error mentioned earlier when attempting to execute the signOut function. To address this issue, I modified the code by removing the line setting the Authorization header and utilizing a different approach:

signOut: async function() {
  try {
    const request = axios.create({
      baseURL: "http://localhost:3000/users/signout"
    });
    request.defaults.headers.common['Authorization'] = `Bearer ${localStorage.token}`;
    const response = await request.post();
    // continue functionality
  } catch (err) {
    // handle errors
  }
}

This adjustment successfully resolved the problem with the Authorization header. Now, everything functions as expected. If you are facing a similar issue with the initial setup, consider implementing the revised code snippet provided above to ensure correct header setup.

Answer №1

When the authorization header is set in your main.js, it will execute once during app startup. If the token is not present in your localStorage, it will be undefined until a request provides its own token. Alternatively, in the second approach, where the token is available in localStorage, the header will be correctly set.

To address this issue in the first approach, you can remove the assignment of the Authorization header and instead directly assign the token in your requests or create a function to automatically assign the default header auth when the server token changes or is removed.

Update: A more streamlined example using redirect interceptors

axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    const auth = token ? `Bearer ${token}` : '';
    config.headers.common['Authorization'] = auth;
    return config;
  },
  error => Promise.reject(error),
);

This method ensures that before each request, the token is retrieved from localStorage and the updated Bearer token is set in the 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

Adjusting the dimensions of the central container

Does anyone have suggestions on how to resize the middle red container when the window is resized, considering the fixed-width black containers on the left and right? I am aware that this can be achieved using jQuery by calculating the window width and a ...

What is the purpose of the setDrawRange function in the Three.js library?

I've been diving into a three.js codebase. While studying the code and the documentation, there's one thing that's puzzling me. In this particular code snippet. http://jsfiddle.net/w67tzfhx/ there exists the following piece of code. fun ...

What is the correct location to store the bower.json file?

I'm currently using bower 1.2.2 to handle my client-side libraries for the first time with a new node app. I'm unsure whether I should initialize bower in the main project root alongside gruntfile.js and package.json, or within the static directo ...

Error: Attempting to access properties of an undefined object (specifically 'query')

My productController.js const Product = require('../models/product'); const ErrorHandler = require('../utils/errorHandler'); const catchAsyncError = require('../middlewares/catchAsyncErrors'); const APIFeatures = require(&apo ...

Exploring into the subdirectory

I am trying to redirect to a subfolder ASPX page from the index.html page upon page load, but I am encountering an error with the following code: window.location.href = 'URL= HMIS/Login.aspx'</script> Error Resource cannot be found. D ...

Rearrange the text next to the Checkbox using Bootstrap

I'm having trouble aligning the "Default checkbox" text next to the checkbox itself checkbox This is what I've attempted so far <div class="col-2"> <label for="Desc" class="col-sm col-form-label">D ...

Setting up route handlers in Node.js on a pre-initialized HTTP server

Is there a way to add route handlers to an http server that is already instantiated? Most routers, including express, typically need to be passed into the http.createServer() method. For instance, with express: var server = http.createServer(app); My r ...

Using Javascript function with ASP.NET MVC ActionLink

I need help with loading a partial view in a modal popup when clicking on action links. Links: @model IEnumerable<string> <ul> @foreach (var item in Model) { <li> @Html.ActionLink(item, "MyAction", null, new ...

Clicking on a table will toggle the checkboxes

I am facing an issue with this function that needs to work only after the page has finished loading. The problem arises due to a missing semicolon on the true line. Another requirement is that when the checkbox toggle-all is clicked as "checked", I want ...

Floating above a surface to manipulate a title

Wondering if it's possible to achieve this without JavaScript, but that would be the ideal scenario. Here's a snapshot of how my page is structured: ____________________________ | TITLE | |This is a fixed header. I wa ...

Quasar QDrawer module - locking closure

Is there a way to prevent the drawer from closing if the user has unfinished work in it? I want to be able to display a confirmation message, etc... I thought about using something like can-be-closed="canBeClosed", and then I discovered the dial ...

Adjust the style of an element when hovering over a different element

Below is the HTML code in question: <div> class="module-title" <h2 class="title" style="visibility: visible;"> <span>Spantext</span> Nonspantext </h2> </div> I am looking to change th ...

Clients using Socket.io are known to establish connections with various sockets housed within the same server

Hello, I am currently managing a standard chatroom using socket.io but have encountered an issue that I am struggling to troubleshoot. The chatroom appears to be operating normally as clients can send and receive messages. However, there is an occasional ...

Align a collection of images in a grid format on the center of the page with

I am trying to center a div that contains multiple 145px X 145px thumbnail images without setting a fixed width. The goal is to have as many images in each row as the browser window can fit. However, I want to keep the images left-aligned within the center ...

What steps can be taken to ensure that only a single decimal separator is included?

I've created a calculator in HTML with two display screens, operators, and number buttons. The challenge I'm facing is implementing a decimal separator. Initially, I attempted to use a boolean variable as a switch, but the number() function remov ...

Verify that all the input values within the class are empty using jQuery

Within this section, I have multiple input text fields all sharing the same class: <input type="text" class="MyClass"></input> <input type="text" class="MyClass"></input> <input type="text" class="MyClass"></input> My ...

How can we automatically redirect users to an external website based on their responses to a specific question in SurveyJS?

Within my SurveyJS json, I have a radiogroup question that prompts users to make a choice. If they select a specific option, I'd like to redirect them to a different page. Otherwise, I want them to continue with the survey. Is this achievable? (The s ...

The error message "Property 'push' of undefined in AngularJS" occurs when the push method is being called

I'm currently working on developing a basic phonebook web application to enhance my knowledge of Angular, but I've encountered an issue with this error message - "Cannot read property 'push' of undefined". Can anyone help me identify th ...

Utilizing Header and Footer Components in React JS

I'm new to Reactjs(Nextjs) and I am looking to create a "header" and "footer" file that can be used on all pages. I would like to know the best approach to achieve this. Should I create a "Layout.js" file and then call the Header within it? Or should ...

What is the best way to combine an additional array into a different project attribute?

There are 2 arrays being used. This is the content of userGroups: console.log(this.items) [ { "id": 63, "name": "URLGROUP-1643836551908" } ] The contents of urls are shown below: userGroup can contain ...