【问题标题】:Error response is undefined when I get 504 error in axios当我在 axios 中收到 504 错误时,错误响应未定义
【发布时间】:2021-05-07 05:31:41
【问题描述】:

如果我收到任何 404 错误,则在 catch 块中记录错误具有该状态代码,但如果我从服务器收到 504 错误,则在 catch 中记录 error.response 是未定义的。发生这种情况的任何原因?

try {
  const response = await axios.request({
    method,
    url,
    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;
  }
}

【问题讨论】:

  • 我在这里转载了你的问题~jsfiddle.net/vjf85e94。如果我用 curl 打https://httpstat.us/504/cors,它似乎工作得很好。但是,当请求来自浏览器(使用 axiosfetch)时,由于 CORS 错误,它会失败。同样的事情发生在 502

标签: javascript axios


【解决方案1】:
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;
  }
}

超时的默认 axios 行为为 0,表示没有超时。因此,如果请求花费更多时间,它将永远不会被捕获。尝试专门为请求添加超时,然后 axios 将中止请求,并出现可以在 catch 块中捕获的错误。在上面的示例中,我添加了 1 秒超时。

【讨论】:

  • 问题与axios超时无关。服务器发送一个状态为 504 的响应,axios 接收到这个响应,并将其解释为“错误”,从而调用了 catch。如果你设置了 axios 的超时时间,axios 就会停下来尝试接收响应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-03
  • 2019-08-03
  • 2022-06-27
  • 1970-01-01
  • 2015-10-20
相关资源
最近更新 更多