Javascript 如何使用 axios 拦截器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52737078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:01:04  来源:igfitidea点击:

How can you use axios interceptors?

javascriptaxios

提问by Akash Salunkhe

I have seen axios documentation, but all it says is

我看过 axios 文档,但它所说的只是

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
  // Do something with response data
  return response;
}, function (error) {
  // Do something with response error
  return Promise.reject(error);
});

Also many tutorials only show this code but I am confused what it is used for, can someone please give me simple example to follow.

还有很多教程只展示了这段代码,但我很困惑它的用途,有人可以给我简单的例子来遵循。

回答by Aseem Upadhyay

To talk in simple terms, it is more of a checkpoint for every http action. Every api call that has been made, is passed through this interceptor.

简单来说,它更像是每个 http 操作的检查点。已进行的每个 api 调用都通过此拦截器传递。

So, why two interceptors?

那么,为什么有两个拦截器?

An api call is made up of two halves, a request and a response. Since, it behaves like a checkpoint, the request and the response have separate interceptors.

一个 api 调用由两部分组成,一个请求和一个响应。由于它的行为类似于检查点,因此请求和响应具有单独的拦截器。

Some request interceptor use cases -

一些请求拦截器用例 -

Assume you want to check before making a request, are your credentials valid? So, instead of actually making an api call, you can check it at the interceptor level that are your credentials valid.

假设您想在提出请求之前进行检查,您的凭据是否有效?因此,您可以在拦截器级别检查您的凭据是否有效,而不是实际进行 api 调用。

Assume you need to attach a token to every request made, instead of duplicating the token addition logic at every axios call, you can make an interceptor which attaches a token on every request that is made.

假设您需要为每个请求附加一个令牌,而不是在每次 axios 调用时复制令牌添加逻辑,您可以创建一个拦截器,为每个请求附加一个令牌。

Some response interceptor use cases -

一些响应拦截器用例 -

Assume you got a response, and judging by the api responses you want to deduce that the user is logged in. So, in the response interceptor you can initialize a class that handles the user logged in state and update it accordingly on the response object you received.

假设你得到了一个响应,并根据你想要推断用户登录的 api 响应来判断。因此,在响应拦截器中,你可以初始化一个处理用户登录状态的类,并在你的响应对象上相应地更新它已收到。

Assume you have requested some api with valid api credentials, but you do not have the valid role to access the data. So, you can tigger an alert from the response interceptor saying that the user is not allowed. This way you'll be saved from the unauthorized api error handling that you would have to perform on every axios request that you made.

假设您已请求一些具有有效 api 凭据的 api,但您没有访问数据的有效角色。因此,您可以触发来自响应拦截器的警报,指出不允许该用户。通过这种方式,您将免于未经授权的 api 错误处理,而您必须对您发出的每个 axios 请求执行这些错误处理。

Could come up with these use cases right now.

现在可以想出这些用例。

Hope this helps :)

希望这可以帮助 :)

EDIT

编辑

Since this answer is gaining traction, here are some code examples

由于这个答案越来越受欢迎,这里有一些代码示例

The request interceptor

请求拦截器

=> One can print the configuration object of axios (if need be) by doing (in this case, by checking the environment variable):

=> 可以通过执行(在这种情况下,通过检查环境变量)来打印 axios 的配置对象(如果需要):

const DEBUG = process.env.NODE_ENV === "development";

axios.interceptors.request.use((config) => {
    /** In dev, intercepts request and logs it into console for dev */
    if (DEBUG) { console.info("?? ", config); }
    return config;
}, (error) => {
    if (DEBUG) { console.error("?? ", error); }
    return Promise.reject(error);
});

=> If one wants to check what headers are being passed/add any more generic headers, it is available in the config.headersobject. For example:

=> 如果您想检查正在传递哪些标头/添加更多通用标头,它在config.headers对象中可用。例如:

axios.interceptors.request.use((config) => {
    config.headers.genericKey = "someGenericValue";
    return config;
}, (error) => {
    return Promise.reject(error);
});

=> In case it's a GETrequest, the query parameters being sent can be found in config.paramsobject.

=> 如果是GET请求,发送的查询参数可以在config.paramsobject 中找到。

The response interceptor

响应拦截器

=> You can even optionallyparse the api response at the interceptor level and pass the parsed response down instead of the original response. It might save you the time of writing the parsing logic again and again in case the api is used in the same way in multiple places. One way to do that is by passing an extra parameter in the api-requestand use the same parameter in the response interceptor to perform your action. For example:

=> 您甚至可以选择在拦截器级别解析 api 响应,并将解析的响应而不是原始响应向下传递。如果 api 在多个地方以相同的方式使用,它可能会节省您一次又一次地编写解析逻辑的时间。一种方法是在 中传递一个额外的参数,api-request并在响应拦截器中使用相同的参数来执行您的操作。例如:

//Assume we pass an extra parameter "parse: true" 
axios.get("/city-list", { parse: true });

Once, in the response interceptor, we can use it like:

有一次,在响应拦截器中,我们可以像这样使用它:

axios.interceptors.response.use((response) => {
    if (response.config.parse) {
        //perform the manipulation here and change the response object
    }
    return response;
}, (error) => {
    return Promise.reject(error.message);
});

So, in this case, whenever there is a parseobject in response.config, the manipulation is done, for rest of the cases, it'll work as is.

因此,在这种情况下,只要 中有parse对象response.config,操作就会完成,对于其余情况,它将按原样工作。

=> You can even view the arriving HTTPcodes and then make the decision. For example:

=> 您甚至可以查看到达的HTTP代码,然后做出决定。例如:

axios.interceptors.response.use((response) => {
    if(response.status === 401) {
         alert("You are not authorized");
    }
    return response;
}, (error) => {
    if (error.response && error.response.data) {
        return Promise.reject(error.response.data);
    }
    return Promise.reject(error.message);
});

回答by Constantin Chirila

It is like a middle-ware, basically it is added on any request (be it GET, POST, PUT, DELETE) or on any response (the response you get from the server). It is often used for cases where authorisation is involved.

它就像一个中间件,基本上它被添加到任何请求(GET、POST、PUT、DELETE)或任何响应(您从服务器获得的响应)上。它通常用于涉及授权的情况。

Have a look at this: Axios interceptors and asynchronous login

看看这个:Axios拦截器和异步登录

Here is another article about this, with a different example: https://medium.com/@danielalvidrez/handling-error-responses-with-grace-b6fd3c5886f0

这是另一篇关于此的文章,有一个不同的例子:https: //medium.com/@danielalvidrez/handling-error-responses-with-grace-b6fd3c5886f0

So the gist of one of the examples is that you could use interceptor to detect if your authorisation token is expired ( if you get 403 for example ) and to redirect the page.

因此,其中一个示例的要点是您可以使用拦截器来检测您的授权令牌是否已过期(例如,如果您获得 403)并重定向页面。