Javascript 捕获应用程序范围内的axios请求错误
在我的SPA中,我使用axios向API发出请求。我目前使用axios请求拦截器向请求添加身份验证头,但我还想使用它们捕获401个错误并删除本地存储的身份验证令牌 我试图将其添加到当前拦截器Javascript 捕获应用程序范围内的axios请求错误,javascript,axios,Javascript,Axios,在我的SPA中,我使用axios向API发出请求。我目前使用axios请求拦截器向请求添加身份验证头,但我还想使用它们捕获401个错误并删除本地存储的身份验证令牌 我试图将其添加到当前拦截器 axios.interceptors.response.use((response) => { // Set user headers only if they are not blank. // If DTA gets a lot of request quic
axios.interceptors.response.use((response) => {
// Set user headers only if they are not blank.
// If DTA gets a lot of request quickly, it won't return headers for some requests
// so you need a way to keep headers in localStorage to getting set to undefined
if (response.headers['access-token']) {
localStorage.setItem('access-token', response.headers['access-token'])
localStorage.setItem('client', response.headers.client)
localStorage.setItem('uid', response.headers.uid)
localStorage.setItem('token-type', response.headers['token-type'])
}
if (response.status === 401) {
localStorage.setItem('access-token', '')
localStorage.setItem('client', '')
localStorage.setItem('uid', '')
localStorage.setItem('token-type', '')
}
// You have to return the response here or you won't have access to it
// later
return response
})
但我发现当状态返回错误代码时,拦截器似乎没有运行。是否有任何方法可以在应用程序范围内捕获这些错误,而不必手动将此错误处理添加到每个请求?要处理响应中的错误,需要使用响应拦截器中回调的第二个参数
axios.interceptors.response.use((response) => {
// Set user headers only if they are not blank.
// If DTA gets a lot of request quickly, it won't return headers for some requests
// so you need a way to keep headers in localStorage to getting set to undefined
if (response.headers['access-token']) {
localStorage.setItem('access-token', response.headers['access-token']);
localStorage.setItem('client', response.headers.client);
localStorage.setItem('uid', response.headers.uid);
localStorage.setItem('token-type', response.headers['token-type']);
}
// You have to return the response here or you won't have access to it
// later
return response;
}, (error) => {
// do what you want to do when error happens
if (error.response.status === 401) {
localStorage.setItem('access-token', '');
localStorage.setItem('client', '');
localStorage.setItem('uid', '');
localStorage.setItem('token-type', '');
}
else if(error.response.status === 500) {
// do something for all 500 errors
} else {
// do something for all other error codes
}
// should reject the promise so your api call goes to catch block
return Promise.reject(error);
});
有关更多信息,请参阅
我在npm上发布了一个axios拦截器库。有关拦截器中错误处理的更多详细信息,请参阅源代码
向拦截器“errorresponseHandler”添加第二个函数:
function errorResponseHandler(error) {
}
// apply interceptor on response
axios.interceptors.response.use(
response => response,
errorResponseHandler
);
您可以定义并导出一个错误处理函数,该函数在一个helper、util等类中接受一个
error
参数,然后您可以在每个catch块中使用一行调用此方法
或者
您可以定义一个
doRequest()
方法来处理进程的发送和响应处理,并向该方法提供与自定义请求相关的参数,例如{url:'a',method:X,data:Y}
,从任何地方调用此帮助器方法 错误
似乎是单个字符串(错误:“请求失败,状态代码401”)。错误。状态代码未定义