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

Javascript axios库中的超时功能不起作用,javascript,ajax,xmlhttprequest,redux,axios,Javascript,Ajax,Xmlhttprequest,Redux,Axios,我已经设置了axios.defaults.timeout=1000 我停止了为我提供API的服务器 但发送请求后超时需要1s以上的时间 我的请求是这样的: import axios from 'axios'; axios.defaults.timeout = 1000; return axios.post(`${ROOT_URL}/login/${role}`, creds).then((response) => { console.log(response);

我已经设置了
axios.defaults.timeout=1000

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

但发送请求后超时需要1s以上的时间

我的请求是这样的:

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;
      });
我也尝试过:

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

const httpClient = axios.create();

httpClient.defaults.timeout = 500;

return httpClient.post(`${ROOT_URL}/login/${role}`, creds)
  .then(handleResponse)
Axios不会停止抓取,5-10分钟后,它最终显示网络错误。我知道还有其他技术可以处理超时,但为什么axios中的超时功能不起作用呢?axios不停止抓取的原因可能是什么

编辑: 如评论中所述,我也尝试过:

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

const httpClient = axios.create();

httpClient.defaults.timeout = 500;

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

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

const httpClient = axios.create();
httpClient.defaults.timeout = 500;
然后,您可以按如下方式使用httpClient:

return httpClient.post(`${ROOT_URL}/login/${role}`, creds)
  .then(handleResponse)
另一方面,您也可以在同一配置中设置基本url,而不是使用
${ROOT\u url}

httpClient.defaults.baseURL = ROOT_URL

此代码适用于我:

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);
});
若服务器在5秒内并没有响应,它将进入catch块

这也很有用:

由此(多亏了zhuyifan2013给出的解决方案),我发现axios
timeout
是响应超时,而不是连接超时

假设您通过axios请求URL,服务器需要很长时间才能响应,在这种情况下,axios超时将正常工作

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

您必须使用以下代码

  const source = CancelToken.source();
  const timeout = setTimeout(() => {
    source.cancel();
    // Timeout Logic
  }, 10000);
  
  axios.get(ip + '/config', {cancelToken: source.token}).then((result) => {
    // Clear The Timeout
    clearTimeout(timeout);

    // Handle your response
  });

请注意,如果您有有效的连接,仍然会执行超时逻辑块。因此,您必须清除
超时

我在使用RN的Android上遇到了相同的问题

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
  }
 }
我通过添加以下内容解决了问题:

<application 
  ... 
  // add this 
  android:usesCleartextTraffic="true"> 

我的react native有这个问题。解决办法是:

  • 创建一个文件“CustomClientFactory.java”,并将以下代码放在其中:
  • 您可以在下面的链接中详细解释超时:


    1。我想您应该返回httpClient.post(
    ${ROOT\u URL}/login/${role}
    ,creds)2。我也试过这个。没用。3.目前,我在这里使用的是mislav提到的一种技术:工作起来像一个符咒,但我希望axios提供的超时能起作用。我不知道为什么这对你不起作用。您使用的是哪个版本的axios
    ?您能否将您的
    require
    /
    import
    语句和axios初始化代码包含在上述内容中?虽然此链接可以回答问题,但最好将答案的基本部分包含在此处,并提供链接供参考。如果链接页面发生更改,仅链接的答案可能无效。-@DanielCottone请仔细复习。这也是一个答案,但当我设置超时:9999999时,会出现错误:“net::ERR_CONNECTION_densed”而不是“超过9999999 ms超时”。当我将超时设置为大于5000时,我想添加,如果您在角度方面有此问题,您只需添加
    .pipe(超时(timeout_MILLIS))
    到observable.axios使用XMLHttpRequest for browser env,如果>但您没有internet连接-它将是一个net::ERR_internet_断开的连接,因此我认为没有必要使用axios(或任何其他)超时。它仅适用于nodejs env。浏览器可以做的所有其他事情。因此,如果你真的想设置连接超时,你可以尝试从axios获取一个请求对象并检查readyState——直到它打开(1)——它还没有连接。我不明白他们为什么不在库中实现这一点,而不是给我们一个中断的超时选项。他们只是解决了这个问题而没有修复它…抱歉,但这与axios库无关这是android问题,不是axios问题。你们为什么要在
    javascript
    标签下发布android/java内容?这是不一样的。。。