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

Muh*_*qib 5 javascript http node.js axios

我正在使用 axios 发出 HTTP 请求并收到错误。这是axios 文档中有关错误处理的片段。

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);
  });
Run Code Online (Sandbox Code Playgroud)

就我而言,结果error.request是正确的,这意味着(根据文档)发出了请求但没有收到响应。我的问题是,可能是什么原因造成的?发出请求但未收到响应的情况是什么?

谢谢

jfr*_*d00 0

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

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

您可以显着增加 axios 调用的超时值,以测试 #2 是否发生了这种情况。