Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameter/argument to axios interceptor

Tags:

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.

like image 382
Fredrik Avatar asked Dec 09 '17 14:12

Fredrik


People also ask

How do you pass parameters to Axios interceptor?

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.

How do you intercept an Axios?

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.

Why do we use interceptors in Axios?

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.


1 Answers

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.

like image 149
Rosdi Kasim Avatar answered Sep 18 '22 14:09

Rosdi Kasim