Javascript 当我在axios中获得504错误时,错误响应未定义
如果我收到任何404错误,则在catch块中记录错误时会显示该状态代码,但如果我从服务器收到504错误,则在catch中记录error.response是未定义的。为什么会这样Javascript 当我在axios中获得504错误时,错误响应未定义,javascript,axios,Javascript,Axios,如果我收到任何404错误,则在catch块中记录错误时会显示该状态代码,但如果我从服务器收到504错误,则在catch中记录error.response是未定义的。为什么会这样 试试看{ const response=等待axios.request({ 方法 网址, 标题:{ “内容类型”:“应用程序/json;字符集=UTF-8”, }, …配置, }); 返回响应; }捕获(错误){ console.dir(错误); if(error.response&&error.response.sta
试试看{
const response=等待axios.request({
方法
网址,
标题:{
“内容类型”:“应用程序/json;字符集=UTF-8”,
},
…配置,
});
返回响应;
}捕获(错误){
console.dir(错误);
if(error.response&&error.response.status==401){
const isnoauthURL=window.location.pathname.match(/\/verify\/);
如果(!IsNoAuthUrl){
localStorage.clear();
window.location.reload();
}否则{
投掷误差;
}
}否则{
投掷误差;
}
}
超时的默认axios行为为0,表示没有超时。因此,如果请求需要更多时间,它将永远不会被捕获。尝试专门为请求添加超时,然后axios将中止请求,并出现一个可以在catch块中捕获的错误。在上面的示例中,我添加了1秒超时。我在这里复制了您的问题~。如果我点击
https://httpstat.us/504/cors
使用curl,效果似乎很好。但是,当请求来自浏览器时(使用axios
或fetch
),由于CORS错误而失败。502也会发生同样的事情
try {
const response = await axios.request({
method,
url,
timeout: 1000, //1000ms
headers: {
'Content-Type': 'application/json;charset=UTF-8',
},
...config,
});
return response;
} catch (error) {
console.dir(error);
if (error.response && error.response.status === 401) {
const isNonAuthUrl = window.location.pathname.match(/\/verify\//);
if (!isNonAuthUrl) {
localStorage.clear();
window.location.reload();
} else {
throw error;
}
} else {
throw error;
}
}