攔截器

2020-02-06 16:25 更新

在請求或響應被 then 或 catch 處理前攔截它們。

// 添加請求攔截器
axios.interceptors.request.use(
    function (config) {
        // 在發(fā)送請求之前做些什么
        return config;
    },
    function (error) {
        // 對請求錯誤做些什么
        return Promise.reject(error);
    }
);

// 添加響應攔截器
axios.interceptors.response.use(
    function (response) {
        // 對響應數(shù)據做點什么
        return response;
    },
    function (error) {
        // 對響應錯誤做點什么
        return Promise.reject(error);
    }
);


如果你想在稍后移除攔截器,可以這樣:

const myInterceptor = axios.interceptors.request.use(function () { /* ... */ });
axios.interceptors.request.eject(myInterceptor);


可以為自定義 axios 實例添加攔截器:

const instance = axios.create();
instance.interceptors.request.use(function () { /* ... */ });
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號