如何使用 Axios 拦截器处理 API 错误响应
免责声明
这不是最好的解决方案,只是一个解决方案。网上可能有更好、更完善的解决方案,但这个方案实现起来非常简单。
此外,我们假设您使用 来axios
从客户端获取数据。
用例是什么?
假设您的前端应用程序使用一些 API,并且您的 API 需要一些身份验证令牌(例如 JWT 令牌),在每次请求时发送,并且您在登录屏幕后获得此令牌。
JWT 令牌通常有一个有效期,可能是一小时、一天或更长时间(但不应使用超过该时间)。这里我们讨论的是刷新令牌还是实际令牌并不重要,但在某些时候,你调用的 API 可能会因为令牌过期而拒绝你的请求。
解决这个问题的一种方法是在代码中处理请求时进行处理,这样如果请求出错,只需将其重定向回登录屏幕即可。
例如:
import axios from 'axios';
const fetchData = async () => {
try {
const { data } = await axios.get('some/endpoint');
return data;
} catch (error) {
// this failed, so let's redirect to the login page
console.log(error);
window.location.href = '/';
}
}
上述解决方案是可以的,如果你在页面上只发出一个请求,它就可以工作。
但是,这也意味着如果您有多个页面,并且可能在每个页面上进行多个请求,那么这种策略就会变得有点麻烦。
改用 axios 拦截器!
以集中的方式处理同一问题的更好、更简单的方法是使用axios 拦截器。
使用拦截器,您可以挂钩到 API 调用的特定生命周期,request
以及response
,并可能修改它们的行为。
该axios.intercepotrs.request.use(config)
函数有一个参数,即标头的配置,而axios.intercepotrs.response.use(response, error)
有两个,分别与.then
(成功响应)和.catch
(当我们收到错误(任何非 2xx 的状态)作为响应时)挂钩。
例如,在下面的例子中,我们将告诉 axios 在我们发出的每个请求上执行代码:
import axios from 'axios';
axios.interceptors.response.use(
response => response,
error => {
window.location.href = '/';
});
正如您上面看到的,我们对响应不做任何处理,但如果error
调用,我们会重定向到我们的登录页面。
注意:您不需要对每个文件都执行此操作,只需执行一次,例如在配置文件上。
如果您想要更好地控制,比如您只想针对某些特定的 http 状态代码,比如401 Unauthorized
,您可以通过访问它error.response.status
,所以我们的代码将如下所示:
axios.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
window.location.href = '/';
}
});
您是否只想处理某些请求?
那么,您也可以创建一个 axios 实例,并仅将该实例用于某些调用,例如:
// lib/customAxios.js
export const customAxios = axios.create({
baseURL: 'http://yourcoolapi.com/api',
headers: {
'X-Custom-Header': 'foobar'
}
});
customAxios.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
window.location.href = '/';
}
});
export default customAxios;
// yourcode.js
import customAxios from '/lib/customAxios.js';
const fetchData = async () => {
try {
const { data } = await customAxios.get('some/endpoint');
return data;
} catch (error) {
// this failed, so let's redirect to the login page
console.log(error);
}
}
再次强调,这只是一个关于如何使用 axios 拦截器的简单用例,其他策略可能效果一样好,甚至更好。
另一种策略可能是使用request
拦截器,在实际调用 API 之前检查 JWT 令牌,然后请求新的令牌,或者重定向到登录页面,等等。
但我在这篇文章中解释的方案可能是最容易理解和操作的。