将 parameter/argument 传递给 axios 拦截器

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);
});

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

我最终使用了 headers object。不确定是否推荐这样做,或者是否 anti-pattern。但无论如何它有效。我不完全确定 header 添加到服务器请求头的字节数,但我认为它可以忽略不计。

工作解决方案

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

axios.interceptors.request.use((config) => {
  config.params = {my_variable: 'value'}
  return config
})

@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.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时我可以将数据传递给拦截器而不是服务器”之类的问题,答案是肯定的。虽然它没有记录并且在使用打字稿时你必须添加 //@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);
});