"Encountering an issue with adjusting axios default headers on a global scale in

In main.js

import axios from 'axios';

axios.defaults.headers.common = {
    'Authorization': 'JWT ' + Vue.auth.getToken()
};

axios.defaults.baseURL = process.env.VUE_APP_BASE_URL; //TODO: ensure the trailing slash is appended

// Add modified axios instance to Vue prototype so that it is available globally via Vue instance
Vue.prototype.$http = axios;

Everything was working fine until this point. (I could successfully log in and store the token)

However, I have encountered an issue with another component that fetches a list of users from the server through an ajax call in the component's created() lifecycle hook. The problem arises when I try to access this.$http within the component - I receive a 401 error response from the server because the Authorization header is not included in the request headers, despite having pre-configured axios.defaults.headers.common.

What's strange is that if I manually refresh the page, the token is correctly attached to the request header and the user list is successfully retrieved**.**

Could someone please provide an explanation for why this behavior is occurring?

Answer №1

One way to globally add headers to your axios requests is by utilizing request interceptors.

axios.interceptors.request.use(function (config) {
// Perform actions before sending the request
  return config;
}, function (error) {
// Handle request error
   return Promise.reject(error);
});

You can access and modify request headers using config.headers. To set headers for the request, you can use the following syntax:

config.headers = {
   'Authorization': 'JWT ' + Vue.auth.getToken()
}

For more information on axios, visit this link.

Answer №2

If you want to consistently add custom headers to your HTTP requests throughout your application, consider creating a global class for handling this functionality.

import axios from 'axios';

/**
 * A wrapper around the axios library that sets a base URL and authentication headers by default
 */
class CustomAxios {
    constructor(baseUrl, bearerToken) {

        return axios.create({
            baseURL: baseUrl,
            headers: {
                Authorization: `Bearer ${bearerToken}`
            }
        });
    }
}

export default CustomAxios;

To use this class in your main app file:

import { CustomAxios } from 'my/custom-class'


const myService = new CustomAxios('baseURL', 'bearerToken');

Answer №3

Have you experimented with utilizing asios.create method?

http/index.js:

import axios from 'axios'
import env from '../config/env'
import store from '../store'

export default (() =>
  axios.create({
    baseURL: env.API_HOST,
    headers: {
      common: {
        Authorization: store.getters['user/getAuthToken']
      }
    }
  }))()

main.js:

import http from './http'

Vue.prototype.$http = http

In addition, I utilize a store action to update the axios client:

updateHTTPClientAuthToken () {
  Vue.prototype.$http.defaults.headers.common.Authorization = this.getters.getAuthToken
}

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

next.js users may encounter a problem with react-table not rendering correctly

Encountering difficulties while attempting to integrate a basic table function into my upcoming application. Despite being a sample output, the function fails to load into the index for some unknown reason! // Layouts import Layout from "../components ...

What is an alternative way to retrieve the page title when the document.title is unavailable?

Is there a way to retrieve the page title when document.title is not available? The code below seems to be the alternative: <title ng-bind="page.title()" class="ng-binding"></title> How can I use JavaScript to obtain the page title? ...

What are some strategies for enhancing the performance of a React application that contains numerous text input fields (implemented using Hooks) within a form?

The Issue at Hand Encountering a challenge with a React form that communicates data via a REST API. The rendering and input processing are noticeably sluggish when dealing with around 80 text fields. Currently, I am utilizing functional components with h ...

Incorporating the Acts_as_votable gem alongside Angularjs for interactive voting functionality

I'm trying to figure out how to implement Acts_as_Votable in an Angular template for a car voting system. Despite my efforts, I can't seem to display the vote count when rendering the list in Angular. I think I may need to establish some kind of ...

Is there a way to navigate to a particular route from a child component using the beforeEnter guard?

Based on the following route configuration, my application should redirect to '/login' if the user is not authenticated : const ifAuthenticated = (to, from, next) => { if(Store.getters.isAuthenticated) { next(); return; } else ...

The response body in Express is returned as a ReadableStream instead of the typical JSON format

When using Express to create an API endpoint, I typically respond with res.json() to send a JSON object in the response that can be consumed by the client. In my API, I am implementing batched promises, resolving them, and sending back an object. However ...

Should I consolidate my ajax requests into groups, or should I send each request individually?

Currently working on an ajax project and feeling a bit confused. I have 3 functions that send data to the server, each with its own specific job. Wondering if it's more efficient to group all the ajax requests from these functions into one big reques ...

Tips for universally updating the FormData TypeScript interface within React Native applications

While attempting a simple append with FormData in React Native like the following... const formData = new FormData(); formData.append('image-data', { uri: '/awesome-chat-app/ImagePicker/abb9-a435046e971c.jpg', name: 'image001. ...

When the position value in three.js exceeds a certain threshold, the mesh starts to jitter uncontrollably

In search of a unique setting, I envision a universe where the gaps between meshes represent incredibly large numbers (for instance 10^15). Despite this vast distance, there is one mesh whose position (x, y, or z) quivers unsettlingly. Even after experimen ...

What is the most effective way to loop and render elements within JSX?

Trying to achieve this functionality: import React from 'react'; export default class HelloWorld extends React.Component { public render(): JSX.Element { let elements = {"0": "aaaaa"}; return ( ...

Securing Routes with Firebase User Authentication in ReactJS

Currently, I am encountering an issue with the auth.onAuthStateChanged function in my Firebase user authentication service integrated with ReactJS. The function fires after the component has already been rendered, causing problems with redirecting users to ...

Customizing the color of text in the fillText() function on an HTML5 <canvas>

I need help changing the color of each line of text in my canvas messages. I've tried creating variables for them, but haven't had any success. Any assistance would be greatly appreciated. function initialize(){ var elem = document.getElemen ...

Error in the delete function on a JSF webpage

I am currently working on implementing a JSF table with a delete button. Below is the JavaScript code that triggers the dialog box: function showDialog(a){ $("<div />", { text: a }).dialog({ width: 600, ...

What is the best way to incorporate spacing between rows in material UI and React?

How do I add spacing between each row in my table using MUI? I've tried using borderSpacing: '0px 10px!important' and borderCollapse: 'separate!important' but it's not working. Any suggestions on how to achieve this with MUI w ...

JQuery isn't functioning properly on dynamically generated divs from JavaScript

I'm currently tackling an assignment as part of my learning journey with The Odin Project. You can check it out here: Despite creating the divs using JavaScript or jQuery as specified in the project requirements, I am unable to get jQuery's .hov ...

The 'hide' property is not recognized on this type during the build process

Just starting out with the quasar framework. I've created a new component and used it in a modal popup. I followed the steps outlined here. The dialog opens using the method below. methods: { openStoreModal(store:Store) { this.$q.dialog({ ...

What is the best way to retrieve this value using javascript?

Currently, I am developing a browser extension for opera that will search for a specific element on the page when clicked. However, as a beginner in HTML and Javascript, I am completely lost and unsure of what steps to take next. The crucial value I need ...

A comparison of parent and child components

To implement a child-parent component relationship in Angular, first create two JSON files: parent.json and child.json. The parent.json file should contain the following data: "Id":10001, "name":"John" "Id":10002, ...

The Bcrypt hashed password does not match the password hash stored in Mongodb

When I use bcrypt.hash to encrypt a password, the hash generated is normal. However, when I save this hashed password in MongoDB using Mongoose, it appears to be different from the original hash. For example: Password hash: $2b$10$bUY/7mrZd3rp1S7NwaZko.S ...

Unleashing the power of Vuex with promise chaining

One challenge I am facing is making API calls to retrieve an array of endpoints, which are then used to fetch data from another API. // Raise isLoading flag this.$store.commit('isLoading', true); // Initial data fetch this.$s ...