Skip to content

Axios: How to Set Timeout for Request

Last updated on July 7, 2023

To set timeouts for requests in Axios, you can use the timeout configuration option. Here’s an example of how to set a timeout for a request:

import axios from 'axios';

axios.get('/api/data', {
  timeout: 5000 // Set the timeout value in milliseconds (e.g., 5 seconds)
})
  .then(response => {
    // Process the response
    console.log(response.data);
  })
  .catch(error => {
    // Handle errors
    console.error('Error:', error.message);
  });

In the example above, we make a GET request to /api/data and set the timeout option to 5000 milliseconds (5 seconds). If the request takes longer than the specified timeout, Axios will throw a timeout error and the request will be canceled.

You can adjust the timeout value according to your needs by providing the desired timeout value in milliseconds.

In the event of a timeout, the request will be rejected and the catch block will handle the timeout error. You can customize the error-handling logic as per your requirements.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments