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.
To pass parameter or argument to Axios interceptor with JavaScript, we can add it to the config. params object. We add the myVar property to config. params by spreading its existing properties into a new object and then add myVar after it.
Upon sending a request, we'll receive either a success response or an error response. In axios , the success response is handled in the then block, and the error is handled inside the catch block. Using Interceptors , we can intercept the requests or responses before they are handled by the then or catch block.
Axios interceptors are functions that Axios calls for every request. You can use interceptors to transform the request before Axios sends it, or transform the response before Axios returns the response to your code. You can think of interceptors as Axios' equivalent to middleware in Express or Mongoose.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With