Vue.js - 导出一个axios拦截器

Vue.js - Export an axios interceptor

大家晚上好,我的 VueJS 拦截器有问题。我不明白我的问题从何而来,我正在拔头发...

看了几个教程,看了几个关于Whosebug的话题,但是完全不明白是怎么回事。

当我打开调试器时,它被触发了,但是当我切换到“axios.interceptors”时,它告诉我axios是未定义的,它是不可理解的...

import axios from 'axios';

debugger;
axios.interceptors.response.use(function (response) {
    console.log(response);
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
}, function (error) {
    console.log(error);
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
});

const token = localStorage.getItem('token');

export default axios.create({
    baseURL: process.env.VUE_APP_URL_API,
    headers: {
        Authorization: `Bearer ${token}`
    }
})

上面的代码是在我的 VueX Store 中调用的。

import Http from "../../api/http";

export default {
    state: {
        customers: {},
        customer: {},
    },
    getters: {
        customers: state => state.customers,
    },
    mutations: {
        SET_CUSTOMERS(state, customers) {
            state.customers = customers;
        }
    },
    actions: {
        loadCustomers({commit}) {
            Http.get('/customers').then(result => {
                commit('SET_CUSTOMERS', result.data.data );
            }).catch(error => {
                throw new Error(`API ${error}`);
            });
        }
    }
};

我想触发 http 代码 401 以注销我的用户并销毁浏览器中的令牌。

如果有人能帮助我,我会很高兴,非常感谢。

此致, 克里斯托夫

如拦截器docs所示,就在示例拦截器的下方,如果使用实例,则必须为其添加拦截器:

import axios from 'axios';

const token = localStorage.getItem('token');

const instance = axios.create({
    baseURL: process.env.VUE_APP_URL_API,
    headers: {
        Authorization: `Bearer ${token}`
    }
})

instance.interceptors.response.use(function (response) {
    console.log(response);
    // Any status code within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
}, function (error) {
    console.log(error);
    // Any status codes outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
});

export default instance;

对于想知道问题是如何解决的人,这里有我的代码:)

success.js

export default function (response) {
    return response
}

failure.js 从 'vue-router'

导入路由器
export default function (error) {
    switch (error.response.status) {
        case 401:
            localStorage.removeItem('jwt.token')

            router.push({
                name: 'Login'
            })
            break
    }

    return Promise.reject(error)
}

将此添加到 main.js

const token = localStorage.getItem('jwt.token')
if (token) {
    axios.defaults.headers.common.Authorization = token
}

创建 api.js 这是我所有请求的客户端,所以我的请求总是通过它。

import axios from 'axios'
import success from '@/interceptors/response/success'
import failure from '@/interceptors/response/failure'

const api = axios.create({
    baseURL: process.env.VUE_APP_URL_API
})

api.interceptors.request.use((config) => {
    const token = localStorage.getItem('jwt.token')

    config.headers.Authorization = `Bearer ${token}`

    return config
})

api.interceptors.response.use(success, failure)

export default api

希望对你有用:)