How to configure Authorization bearer token in axios?
Asked Answered
D

4

7

Hi I created a login action (using Vuex) which saves a users jwt token to local storage. Inside this login action I call another action to fetch some posts which this user created. It works completely fine when I pass the token in the header of the get request in the fetchPosts action.

async login(context, user){
    try {
       const res = await api.post('/users/login', user)
       localStorage.setItem('jwt', res.data.token)
       context.commit('SET_USER', res.data.user)
       context.dispatch('fetchPosts')
    }catch(err){
       console.log(err.response.data)
    }
}

async fetchPosts(context){
    try {
        const res = await api.get('/posts', {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('jwt')}`
          }
        })
        context.commit('SET_POSTS', res.data)
     }catch(err){
        console.log(err.response.data)
     }
}

The above codes works perfectly fine, but the problem is I have several auth routes and I don't want to pass

headers: { Authorization: `Bearer ${localStorage.getItem('jwt')}`}

for all api requests.

I want to configure in 1 file, which I tried but when I login I get unauthenticated message and when I check in the networks tab I see Bearer null passed into authorization. See below my attempt to configure.

import axios from 'axios'
export default axios.create({
  baseURL: 'http://localhost:3000',
  headers: {
    Authorization: `Bearer ${localStorage.getItem('jwt')}`
  }
})

Anyone know where I went wrong or what I can do to resolve this issue.

Drice answered 11/6, 2021 at 12:39 Comment(1)
This is what Axios interceptors are for.Lock
P
10

Here is a simple example of how to do it.

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

Find more information here

Parolee answered 11/6, 2021 at 13:21 Comment(3)
@Still.Dre Describe how it doesn't work. Are you seeing the header in the request? Is the value wrong?Jelly
@Still.Dre doesn't work is a global concept. Please explain the issue. Are there any errors? How did you implement it? What's wrong?Parolee
also you need to add config.headers = config.headers ?? {};Adame
C
2

You could apply the interceptor directly on your created axios instance

import axios from "axios";

const baseDomain = process.env.VUE_APP_API_URL;

const baseURL = `${baseDomain}`;
const instance = axios.create({
  baseURL
});
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('accesstoken');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }

    return config;
  },

  (error) => {
    return Promise.reject(error);
  }
);

export default instance;

Chicanery answered 6/1, 2022 at 14:5 Comment(0)
T
2
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

https://axios-http.com/docs/config_defaults

Tollbooth answered 24/2, 2022 at 12:17 Comment(0)
G
1

Add this to your main.js file

    axios.interceptors.request.use(config => {
      const token = localStorage.getItem("jwt");
      config.headers["Authorization"] = `Bearer ${token}`;
      return config;
    });
Gainsborough answered 11/6, 2021 at 13:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.