最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to configure Authorization bearer token in axios? - Stack Overflow

programmeradmin2浏览0评论

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)
       contextmit('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')}`
          }
        })
        contextmit('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.

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.

Share Improve this question edited Jun 11, 2021 at 13:37 CyberEternal 2,5452 gold badges14 silver badges36 bronze badges asked Jun 11, 2021 at 12:39 Sy3dSy3d 2692 gold badges5 silver badges20 bronze badges 1
  • 3 This is what Axios interceptors are for. – Estus Flask Commented Jun 11, 2021 at 12:49
Add a comment  | 

4 Answers 4

Reset to default 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

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;

axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

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

Add this to your main.js file

    axios.interceptors.request.use(config => {
      const token = localStorage.getItem("jwt");
      config.headers["Authorization"] = `Bearer ${token}`;
      return config;
    });
发布评论

评论列表(0)

  1. 暂无评论