[英]Pass parameter/argument to axios interceptor
如何將自定義參數發送到axios攔截器? 我正在使用這樣的攔截器:
window.axios.interceptors.request.use(function (config) {
if (PASSED_PARAM == true) {
doSomethingAwesome();
}
return config;
}, function (error) {
return Promise.reject(error);
});
我還有一個需要接收相同參數的響應攔截器。
@Laurent 建議的方法將導致 axios 清除所有其他參數並將其替換為my_variable
,這可能不是您想要的。
添加默認參數而不是替換它的正確方法是這樣的:
axios.defaults.params = {};
axios.interceptors.request.use(function (config) {
config.params['blah-defaut-param'] = 'blah-blah-default-value';
return config;
}, function (error) {
return Promise.reject(error);
});
這適用於 axios 0.18.1
。 由於回歸錯誤,它不適用於 axios 0.19
...,我相信它會很快得到修復。
合並參數
axios.interceptors.request.use((config) => {
config.params = {...config.params, my_variable: 'value'}
return config
})
當您發送數據時,使用 Axios 攔截器向查詢添加參數實際上相當簡單。
axios.interceptors.request.use((config) => {
config.params = {my_variable: 'value'}
return config
})
我最終使用了headers
對象。 不確定這是推薦的,還是反模式的。 但無論如何它都有效。 我不完全確定標頭向服務器請求標頭添加了多少字節,但我認為這是可以忽略的。
axios 允許傳遞一些額外的請求參數:
axios.post('/api', `some body`,
{headers: {'Content-Type': ' text/html;charset=UTF-8'},
param: true});
和攔截器:
this.axios.interceptors.request.use(req => {
console.log(`${req.method}: ${req.param}`); //output: `/api: true`
return req;
});
我已經在版本上測試過:0.21.1
接受的答案以及此頁面上的答案似乎錯過了問題的要求。
這個問題問的是“當我調用 axios 時,我可以將數據傳遞給攔截器而不是服務器”,答案是肯定的。 雖然它沒有記錄,並且在使用 typescript 時,您必須添加 //@ts-ignore。
當您調用 axios 時,您可以傳遞一個配置對象(在 url 之后,或者如果您沒有使用 .get/.post 之類的快捷方法,則 axios 函數只需要一個配置對象。好消息是配置對象是總是與響應一起傳遞,因此您可以在攔截器和承諾處理程序中獲取它。
它在響應對象上作為response.config
可用,在錯誤上作為error.response.config
//@ts-ignore -- typescript will complain that your param isn't expected on the config object.
axios({
method: "get",
url: '/myapi/gocrazy',
// just piggyback any data you want to the end of config, just don't
// use any key's that axios is already expecting
PASSED_PARAM: true
}
//in the interceptor, config is attached to the object, and it keeps any extra keys you tacked on the end.
window.axios.interceptors.request.use(function (config) {
if (config.PASSED_PARAM == true) {
doSomethingAwesome();
}
return config;
}, function (error) {
return Promise.reject(error);
});
window.axios.interceptors.response.use(function (response) {
if (response.config.PASSED_PARAM == true) {
doSomethingAwesome();
}
return response;
}, function (error) {
if (error.response.config.PASSED_PARAM == true) {
doSomethingElseAwesome();
}
return Promise.reject(error);
});
您不能傳遞參數,但可以更新傳遞的參數config
。 請求攔截器邏輯在執行請求之前運行。 它有點像中間件所以也許您需要訪問令牌並更新請求標頭
axios.interceptors.request.use(
(config) => {
// or maybe you need to read the stored cookies
const user = localStorage.getItem("user");
if (user) {
// If user exists get the token
const token = JSON.parse(user).token;
// and then update the headers
config.headers.Authorization = `Bearer ${token}`;
}
// maybe u need to refresh the access tokens, you do it in interceptor
return config;
},
(err) => {
return Promise.reject(err);
}
);
除了DiamondDrake的答案之外,還可以覆蓋全局類型,而不必“ts-ignore”用法:
declare module 'axios' {
interface AxiosRequestConfig extends OriginalAxiosRequestConfig {
PASSED_PARAM: boolean;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.