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

查看:22
本文介绍了你如何使用 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.

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

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 if your credentials are valid. So, instead of actually making an API call, you can check at the interceptor level that your credentials are 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 that 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,但您没有访问数据的有效角色.因此,您可以触发来自响应拦截器的警报,提示用户不被允许.这样,您就可以避免未经授权的 API 错误处理,而您必须对您发出的每个 Axios 请求执行这些操作.

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

这里是一些代码示例

请求拦截器

  • 可以通过执行以下操作(在这种情况下,通过检查环境变量)来打印 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.

    响应拦截器

    • 您甚至可以可选地在拦截器级别解析 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 the 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天全站免登陆