axios库中的超时功能无效

ras*_*tay 20 javascript ajax xmlhttprequest redux axios

我已经设定 axios.defaults.timeout = 1000;

我停止了为我提供API的服务器.

但发送请求后超时需要1秒以上.

这是我的请求的样子:

import axios from 'axios';
axios.defaults.timeout = 1000;

return axios.post(`${ROOT_URL}/login/${role}`, creds).then((response) => {
      console.log(response);

        if(response.status === 200) {
          // If login was successful, set the token in local storage
          localStorage.setItem(`${role}_log_toks`, JSON.stringify(response.data));

          // Dispatch the success action
          dispatch(receiveLogin(response.data));

          return response;
        }
      }).catch(err => {
        console.log(err);
        // If there was a problem, we want to
        // dispatch the error condition
        if(err.data && err.status === 404) {
          dispatch(loginError(err.data));
        } else {
          dispatch(loginError('Please check your network connection and try again.'));
        }

        return err;
      });
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

return axios.post(`${ROOT_URL}/login/${role}`, creds, {timeout: 1000}).then...
Run Code Online (Sandbox Code Playgroud)

Axios不会停止提取,并在5-10分钟后最终显示网络错误.我知道还有其他技术可以处理超时,但为什么axios中的超时功能不起作用?什么可能是axios不停止提取的原因?

Axios版本0.9.1

编辑: 正如评论中所提到的,我也尝试过:

import axios from 'axios';

const httpClient = axios.create();

httpClient.defaults.timeout = 500;

return httpClient.post(`${ROOT_URL}/login/${role}`, creds)
  .then(handleResponse)
Run Code Online (Sandbox Code Playgroud)

Cla*_*kie 13

您需要创建axios http客户端的实例:

const httpClient = axios.create();
httpClient.defaults.timeout = 500;
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用httpClient,如下所示:

return httpClient.post(`${ROOT_URL}/login/${role}`, creds)
  .then(handleResponse)
Run Code Online (Sandbox Code Playgroud)

另外,您还可以在同一个配置中设置基本网址,而不是使用${ROOT_URL}:

httpClient.defaults.baseURL = ROOT_URL
Run Code Online (Sandbox Code Playgroud)

  • 1.我想你想要返回httpClient.post(`$ {ROOT_URL}/login/$ {role}`,creds)2.试过这个.没工作.3.目前,我正在使用mislav提到的技术:https://github.com/github/fetch/issues/175像魅力一样工作,但我希望axios提供的超时工作. (2认同)

Dom*_*olt 12

向@arthankamal 致敬,因为他的答案就是解决方案,这只是更新和后续行动。

CancelToken 从 v0.22.0 开始已弃用,因为他们切换到了 AbortController,所以我更新了他的代码。在此处查看更多信息: https: //axios-http.com/docs/cancellation

TrySending(data) {
    let abortController = new AbortController()
    const timeout = setTimeout(() => {
        abortController.abort()
        console.log("Aborted")
    }, 3000)

    return axios
        .post(
            apiURL,
            data,
            { signal: abortController.signal }
        )
        .then(response => {
            clearTimeout(timeout)
            return true
        })
        .catch(error => false)
}
Run Code Online (Sandbox Code Playgroud)

无论成功与否,都会返回。

一些注意事项:

  • 不值得尝试使用 .finally因为它不起作用
  • 如果被取消,它将直接进入.catch()并且错误将是{ message: 'canceled' }


art*_*mal 8

从这个axios问题(感谢zhuyifan2013提供解决方案),我发现axios timeout响应超时而不是连接超时

假设您已经通过axios请求了URL,并且服务器花费了很长时间进行响应,在这种情况下,axios超时将起作用。

但是您没有Internet连接,或者您没有要求的IP地址或域名,在这种情况下,axios超时将不起作用。

您必须使用以下代码

  let source = CancelToken.source();
  setTimeout(() => {
    source.cancel();
    // Timeout Logic
  }, 10000);

  axios.get(ip + '/config', {cancelToken: source.token}).then((result) => {
    // Handle your response
  });
Run Code Online (Sandbox Code Playgroud)

请注意,如果您具有有效的连接,则仍将执行“ 超时逻辑”块。

  • 我不明白为什么他们不只是在库中实现这一点,而不是给我们一个损坏的超时选项。他们只是关闭了问题而没有修复它...... (2认同)
  • 我感谢@arthankamal 的详尽回答。另一种选择是“Promise.race(axios.get(...), setTimeout(() => {}, 3000))”吗?您还可以在 axios 请求中包含超时,以捕获与连接超时分开的响应超时。 (2认同)

Ali*_*esh 6

该代码对我有用:

axios({
  method: "post",
  url: 'http://example.com/api',
  timeout: 1000 * 5, // Wait for 5 seconds
  headers: {
    "Content-Type": "application/json"
  },
  data: {
    id: 1234
  }
})
  .then(response => {
    const serverResponse = response.data;
    // do sth ...
  })
  .catch(error => {
    console.log(error);
});
Run Code Online (Sandbox Code Playgroud)

如果服务器在5秒钟内没有响应,它将进入catch块。

这也很有用:#1503


小智 5

submitHashtag = async () => {
  const data = await axios.post('/pwa/basics.php',  {
    withCredentials: true,// if user login
    timeout: 30000
  })
  if (!data) {
    // action here
    alert('reload window')
    return
  }
 }
Run Code Online (Sandbox Code Playgroud)