Timeout feature in the axios library is not working

Shoutout to @arthankamal because his answer is the solution and this is just an update and follow-up.

The CancelToken is deprecated from v0.22.0, because they switched to AbortController, so I updated his code. See more here: 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)
}

This will return if it was succeeded or not.

Some notes:

  • Isn't worth trying using the .finally because it won't work
  • If it was canceled it will go straight to .catch() and the error will be { message: 'canceled' }

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

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

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

You've 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 you've valid connection, still the Timeout Logic block will get executed. So you've 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 won't respond in 5 seconds, it goes into catch block.

This is also useful: #1503


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