使用 Axios 拦截器的 4 种方法
什么是 Axios?
Axios 是一个基于 Promise 的 HTTP 客户端,适用于浏览器和 Node.js。它具有许多实用的默认功能,例如自动检测 JSON 响应并返回对象而非纯文本,如果响应状态码大于 400 则抛出错误。
什么是 axios 拦截器?
Axios拦截器是库每次发送或接收请求时都会调用的一个函数。你可以在“then”或“catch”处理请求或响应之前对其进行拦截。
例子:
// 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) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
您还可以从 Axios 中删除拦截器。
const myInterceptor = axios.interceptors.request.use(function ({/*...*/});
axios.interceptors.request.eject(myInterceptor);
使用拦截器在每个请求中注入身份验证令牌标头
在构建应用程序时,您很可能会使用需要某些凭据(例如 api_token 或用户 Auth 令牌)的 API。通常,您需要在每个 HTTP 请求后附加所需的标头。使用 Axios 拦截器,您只需设置一次,然后在任何调用 Axios 实例的地方,都可以确保令牌的存在。
axios.interceptors.request.use(req => {
// `req` is the Axios request config, so you can modify
// the `headers`.
req.headers.authorization = ‘Bearer mytoken’;
return req;
});
// Automatically sets the authorization header because
// of the request interceptor
const res = await axios.get(‘https://api.example.com’);
使用拦截器记录每个请求和响应。
记录请求非常有用,尤其是在应用程序规模较大且您不知道所有请求触发位置的情况下。使用 Axios 拦截器,您可以快速记录每个请求和响应。
const axios = require(‘axios’);
axios.interceptors.request.use(req => {
console.log(`${JSON.stringify(req, null, 2)}`);
// you must return the request object after you are done
return req;
});
axios.interceptors.response.use(res => {
console.log(res.data.json);
// you must return the response object after you are done
return res;
});
await axios.post(‘https://example.com/‘);
使用 Axios 拦截器进行错误处理
您可以使用 Axios 拦截器捕获所有错误,并在到达最终用户之前对其进行增强。如果您使用多个具有不同错误对象形状的 API,则可以使用拦截器将它们转换为标准结构。
const axios = require(‘axios’);
axios.interceptors.response.use(
res => res,
err => {
throw new Error(err.response.data.message);
}
)
const err = await axios.get(‘http://example.com/notfound’).
catch(err => err);
// “Could not find page /notfound”
err.message;
使用拦截器对请求添加速率限制。
后端资源有限,成本高昂。作为客户端,您可以通过限制 HTTP 调用的速率来减轻服务器负载。以下是使用 Axios 拦截器实现此目的的方法。
const axios = require(‘axios’);
const debounce = require('lodash.debounce');
axios.interceptors.request.use(
res => {
return new Promise((resolve) => {
// only fire a request every 2 sec
debounce(
() => resolve(config),2000);
});
});
}
)