Vue axios使用拦截器更改身份验证标头

时间:2018-09-04 14:48:34

标签: vue.js local-storage axios

我是Vue的新手,并且在这个问题上停留了很长时间。我有一个登录方法,该方法检索API令牌并将其存储在localStorage中。登录API调用是唯一不发送Auth标头的调用。登录后,每次调用都应将API令牌添加到标头中。

登录时,拦截器未设置新标头。需要在浏览器中刷新页面才能工作。为什么会这样,我在做什么错呢?

在我的登录组件中,我有以下方法:

methods: {
    login() {
        api.post('auth/login', {
            email: this.email,
            password: this.password
        })
        .then(response => {
            store.commit('LOGIN');
            localStorage.setItem('api_token', response.data.api_token);
        });
        this.$router.push('reservations') 
    }
}

另外,我有这个axios基本实例和一个拦截器:

export const api = axios.create({
    baseURL: 'http://backend.local/api/',
    // headers: {
    //  'Authorization': 'Bearer ' + localStorage.getItem('api_token')
    // },
    validateStatus: function (status) {
        if (status == 401) {
            router.push('/login');
        } else {
            return status;
        }
    }
});
api.interceptors.request.use((config) => {
    config.headers.Authorization = 'Bearer ' + localStorage.getItem('api_token');
    return config;
}, (error) => {
    return Promise.reject(error);
});

0 个答案:

没有答案
相关问题