攔截器

2020-02-06 16:25 更新

在請(qǐng)求或響應(yīng)被 then 或 catch 處理前攔截它們。

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

// 添加響應(yīng)攔截器
axios.interceptors.response.use(
    function (response) {
        // 對(duì)響應(yīng)數(shù)據(jù)做點(diǎn)什么
        return response;
    },
    function (error) {
        // 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么
        return Promise.reject(error);
    }
);


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

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


可以為自定義 axios 實(shí)例添加攔截器:

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

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)