在什么情况下发出HTTP请求但未收到响应?

时间:2018-09-16 11:26:47

标签: javascript node.js http axios

我正在使用axios发出HTTP请求并收到错误消息。这是snippet from axios docs在谈论错误处理。

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

在我的情况下,error.request确实是真实的,这意味着(根据文档)已提出请求,但未收到响应。我的问题是,可能是什么原因引起的?发出请求但未收到响应的情况是什么?

谢谢

2 个答案:

答案 0 :(得分:0)

如果没有从API端点返回任何响应,则获得.catch()的唯一方法是Axios(或运行Axios的主机系统)实施了超时并且在该超时时间内未收到响应。因此,在没有看到有关您所发出的特定请求和特定API的更多信息的情况下,看来这里有两种可能性:

  1. 您的API端点存在错误,在某些情况下不会发送响应。
  2. 您的API端点要花很长时间发送响应,而Axios库在响应到达之前就已超时。

您可以显着增加axios调用的超时值,以测试#2是否正在发生。

答案 1 :(得分:0)

它经常发生有两个原因:

1。 OPTIONS请求失败。

我执业的主要原因:

  • 服务器检查OPTIONS请求的授权

  • 服务器发送了错误的标头

  • 服务器进行一些重定向

More about OPTIONS requests

2。网络问题。

在具有很多防火墙的公司网络中,我经常看到这一点。如果没有办法解决网络问题,那么主动重试通常会有所帮助。

if (err && err.request && !err.response && navigator.onLine !== false) {
  // try again ...
}
相关问题