Javascript axios 库中的超时功能不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36690451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:26:34  来源:igfitidea点击:

Timeout feature in the axios library is not working

javascriptajaxxmlhttprequestreduxaxios

提问by rash.tay

I have set axios.defaults.timeout = 1000;

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

I stopped the server that provides me with the APIs.

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

But it takes more than 1s to timeout after sending a request.

但是发送请求后超时需要1s以上。

This is how my request looks:

这是我的请求的样子:

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;
      });

I have also tried:

我也试过:

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

Axios doesn't stop fetching and after 5 - 10 minutes it finally shows network error. I understand that there are other techniques to handle timeout but why doesn't the timeout feature in axios work? What could be the reason that axios doesn't stop fetching?

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

Axios version 0.9.1

Axios 0.9.1 版本

EDIT:As mentioned in the comments, I have also tried:

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

import axios from 'axios';

const httpClient = axios.create();

httpClient.defaults.timeout = 500;

return httpClient.post(`${ROOT_URL}/login/${role}`, creds)
  .then(handleResponse)

回答by arthankamal

From this axios issue(Thanks to zhuyifan2013for giving the solution), I've found that axiostimeoutis response timeoutnot connection timeout.

从这个axios 问题(感谢zhuyifan2013提供解决方案),我发现axiostimeoutresponse timeout而不是connection timeout

Let say you've requested the URL through axiosand server is taking long time to respond, in this case the axiostimeout will work.

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

But you don't have internet connection or the IP address or domain name that you're requesting not there, in this case axiostimeout will not work.

但是您没有互联网连接或您请求的 IP 地址或域名不在那里,在这种情况下axios超时将不起作用。

You've to use the following code

您必须使用以下代码

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

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

Please note that if you've valid connection, still the Timeout Logicblock will get executed.

请注意,如果您有有效的连接,仍然会执行超时逻辑块。

回答by Clarkie

You need to create an instance of the axios http client:

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

const httpClient = axios.create();
httpClient.defaults.timeout = 500;

You can then use the httpClient as follows:

然后,您可以按如下方式使用 httpClient:

return httpClient.post(`${ROOT_URL}/login/${role}`, creds)
  .then(handleResponse)

On a side note you can also set the base url in the same config instead of using ${ROOT_URL}:

在旁注中,您还可以在相同的配置中设置基本 url,而不是使用${ROOT_URL}

httpClient.defaults.baseURL = ROOT_URL

回答by Ali Radmanesh

This code works for me:

这段代码对我有用:

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);
});

If server won't respond in 5 seconds, it goes into catch block.

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

This is also useful: #1503

这也很有用:#1503

回答by Naved Khan

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
  }
 }