Need to override the default time out of Axios post request
Asked Answered
C

3

7

When I'm making a post request with axios from client-side(React JS) to the server(spring), the response time of server is more than 2 minutes. So client is not waiting to receive the response when it takes more tan 2 minutes. So I tried to override the default timeout with the below code snippet. But it is not working.Kindly help me to resolve the issue.

const httpClient = Axios.create();
httpClient.defaults.timeout = 240000;

return httpClient.post(url, data).then(
 res => res
).catch(err => err);
Crinite answered 30/1, 2020 at 13:24 Comment(1)
I'd suggest instead splitting that into two stages, see e.g. farazdagi.com/2014/rest-and-long-running-jobsSoothsayer
L
7

If you take a look at the docs (This is another topic but shows an example for timeout).

There is two ways of setting the timeout.

// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
const instance = axios.create();

// Override timeout default for the library
// Now all requests using this instance will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;

// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {
  timeout: 5000
});

You can override the default with instance.defaults.timeout or pass it as an option to your call.

You can also see another example in the docs.

If it isn't working, probably you have a outdated version of axios or you are missing something.

Larynx answered 30/1, 2020 at 13:30 Comment(0)
N
1

When time of creation of axios instance which will be applied to all api calls

const httpClient = Axios.create({ timeout: 2 * 60 * 1000 });

You can pass timeout parameter in api call

httpClient.post(url, data, { timeout: 2 * 60 * 1000 })
Nearly answered 30/1, 2020 at 13:26 Comment(3)
This approach is working fine for the timeout less than 2 minutes. When I try with timeout of 3 minutes, it is throwing error as "Failed to load response data".Crinite
And also we are not able to capture the response with the timeout, getting response as "Failed to load response data"Crinite
When a get a timeout error, response will be empty, nothing,Nearly
G
1

The easiest way to achieve this if you are on nodejs17.3+ is as follows.

await axios({
             method: 'post',
             url: url,
             headers: headers,
             data: payload,
             signal: AbortSignal.timeout(2 * 60 * 1000), // this will handle connection timeout. After waiting for 2 minutes an exception will be thrown
             timeout: 2 * 60 * 1000 // This one handles ONLY response timeout
            })

Note that you have to handle connection timeout and response timeout separately.

Reference: Official documentation

Goosestep answered 8/1 at 4:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.