簡體   English   中英

Vue.js - 導出 axios 攔截器

[英]Vue.js - Export an axios interceptor

大家晚上好,我在 VueJS 中的攔截器有問題。 我不明白我的問題來自哪里,我正在拔頭發......

我看過幾個教程,我看過幾個關於 stackoverflow 的主題,但我根本不明白發生了什么。

當我打開調試器時,它被觸發了,但是當我切換到“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 注銷我的用戶並銷毀瀏覽器中的令牌。

如果有人可以幫助我,我會很高興,非常感謝。

問候,克里斯托夫

如攔截器文檔所示,就在示例攔截器下方,如果您使用實例,則必須將攔截器添加到其中:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM