将参数/参数传递给axios拦截器

Fre*_*rik 3 javascript axios

如何将自定义参数发送到axios拦截器?我正在使用这样的拦截器:

window.axios.interceptors.request.use(function (config) {
    if (PASSED_PARAM == true) {
        doSomethingAwesome();
    }

    return config;
}, function (error) {    
    return Promise.reject(error);
});
Run Code Online (Sandbox Code Playgroud)

我也有一个响应拦截器,需要接收相同的参数。

Dia*_*ake 17

已接受的答案以及本页上的答案似乎错过了问题所要问的内容。

这个问题问的是“当我调用 axios 时我可以将数据传递给拦截器而不是服务器”,答案是肯定的。尽管它没有记录,但在使用打字稿时,您必须添加 //@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);
});
Run Code Online (Sandbox Code Playgroud)


Ros*_*sim 15

@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);
});
Run Code Online (Sandbox Code Playgroud)

这适用于 axios 0.18.10.19由于回归错误,它不适用于 axios ...,我相信它会很快得到修复。

  • 我觉得所有建议的解决方案都不能解决实际问题。我认为问题不在于在拦截器内添加参数,而是在调用例如“axios.get()”时添加选项/参数,这些选项/参数在拦截器内可用(但理想情况下不发送到服务器)。因此拦截器可以区分请求并相应地调整其行为。 (6认同)

小智 14

合并参数

axios.interceptors.request.use((config) => {
  config.params = {...config.params, my_variable: 'value'}
  return config
})
Run Code Online (Sandbox Code Playgroud)


Tom*_* C. 9

axios 允许传递一些额外的请求参数:

axios.post('/api', `some body`,
    {headers: {'Content-Type': ' text/html;charset=UTF-8'},
    param: true});
Run Code Online (Sandbox Code Playgroud)

和拦截器:

 this.axios.interceptors.request.use(req => {   
    console.log(`${req.method}: ${req.param}`); //output: `/api: true`
    return req;
    });
Run Code Online (Sandbox Code Playgroud)

我已经在版本上测试过:0.21.1


Lau*_*ent 8

工作方案

发送数据时,使用Axios拦截器向查询中添加参数实际上相当简单。

axios.interceptors.request.use((config) => {
  config.params = {my_variable: 'value'}
  return config
})
Run Code Online (Sandbox Code Playgroud)