如何使用axios拦截器? [英] How can you use axios interceptors?

查看:821
本文介绍了如何使用axios拦截器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have seen axios documentation, but all it says is

// 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.

推荐答案

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

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.

那么,为什么要使用两个拦截器?

So, why two interceptors?

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

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调用.

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.

假设您需要将令牌附加到每个请求,而不是在每个axios调用中复制令牌添加逻辑,您可以制作一个拦截器,在每个请求上附加一个令牌.

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.

一些响应拦截器用例-

假设您收到一个响应,然后根据要确定用户已登录的api响应进行判断.因此,在响应拦截器中,您可以初始化一个处理用户登录状态的类,并在该类上进行相应的更新.您收到的响应对象.

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凭据的api,但是您没有访问数据的有效角色.因此,您可以从响应拦截器发出警告,说不允许该用户.这样一来,您就可以避免在每次发出的axios请求上必须执行的未经授权的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.

现在可以提出这些用例.

Could come up with these use cases right now.

希望这会有所帮助:)

编辑

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

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

请求拦截器

The request interceptor

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

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

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

=>如果要检查正在传递的标头/添加更多通用标头,则可以在config.headers对象中使用它.例如:

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

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

=>如果是GET请求,则可以在config.params对象中找到正在发送的查询参数.

=> In case it's a GET request, the query parameters being sent can be found in config.params object.

响应拦截器

The response interceptor

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

=> You can even optionally parse 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-request and use the same parameter in the response interceptor to perform your action. For example:

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

因此,在这种情况下,只要response.config中有一个parse对象,就可以完成操作,在其他情况下,它将照常工作.

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

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

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

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

这篇关于如何使用axios拦截器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆