问题
How do I send custom parameters to the axios interceptor? I am using an interceptor like this:
window.axios.interceptors.request.use(function (config) {
if (PASSED_PARAM == true) {
doSomethingAwesome();
}
return config;
}, function (error) {
return Promise.reject(error);
});
I also have a response interceptor that needs to receive the same parameter.
回答1:
The method suggested by @Laurent will cause axios to wipe out all your other parameters and replace it with my_variable, which is may not exactly what you want.
The proper way of adding default parameters instead of replacing it is like this:
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);
});
This works with axios 0.18.1. It does not work with axios 0.19 due to a regression bug..., I believe it will be fixed soon.
回答2:
Working solution
It's actually fairly simple to add parameters to the query with Axios interceptors when you send data.
axios.interceptors.request.use((config) => {
config.params = {my_variable: 'value'}
return config
})
回答3:
Merge params
axios.interceptors.request.use((config) => {
config.params = {...config.params, my_variable: 'value'}
return config
})
回答4:
I ended up using the headers object. Not sure if that is recommended, or if it's anti-pattern. But anyhow it works. I am not entirely sure about how many bytes the header adds to the server request head, but I think it's neglectable.
来源:https://stackoverflow.com/questions/47729790/pass-parameter-argument-to-axios-interceptor