javascript – Timeout feature in the axios library is not working

javascript – Timeout feature in the axios library is not working

From this axios issue (Thanks to zhuyifan2013 for giving the solution), Ive found that axios timeout is response timeout not connection timeout.

Let say youve requested the URL through axios and server is taking long time to respond, in this case the axios timeout will work.

But you dont have internet connection or the IP address or domain name that youre requesting not there, in this case axios timeout will not work.

Youve to use the following code

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

Please note that if youve valid connection, still the Timeout Logic block will get executed. So youve to clear the timeout.

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 wont respond in 5 seconds, it goes into catch block.

This is also useful: #1503

javascript – Timeout feature in the axios library is not working

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

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

You can then use the httpClient as follows:

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

httpClient.defaults.baseURL = ROOT_URL

Leave a Reply

Your email address will not be published.