axios拦截器 config,如何使用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.

解决方案

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?

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.

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.

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.

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.

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.

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):

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.headers object. For example:

axios.interceptors.request.use((config) => {

config.headers.genericKey = "someGenericValue";

return config;

}, (error) => {

return Promise.reject(error);

});

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

The response interceptor

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

});

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.

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

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值