Having issues trying to get timeout
method of axios working.
For testing: I setup a intentionally bad API endpoint: it accepts a request, throws an error (Eg: throw new Error(“testing for timeout”)
) and intentionally does nothing else.
My client app (reactJS) hangs once I make a call to the test API endpoint - I expected it to timeout within 2 seconds (my set timeout). I can verify that the app is making contact with server. Its only when I kill my test API server that my client app immediately continues.
Sample code:
const axios = require('axios')
const test1Press = async () => {
try
{
await axios.post('https://mynodeserver.com/api/debug/throw', {timeout: 2000})
console.log("post call passed")
}
catch (err)
{
console.log("post call failed")
}
}
EDIT (~2020):
On further research, looks like axios timeout
is only for response timeouts but not connection timeouts. Suggested solutions for connection timeouts are cancellation methods (e.g. signal
, cancelToken (deprecated)
):
Tested this and working:
const source = CancelToken.source();
try {
let response = null;
setTimeout(() => {
if (response === null) {
source.cancel();
}
}, 2000);
response = await axios.post('/url',null,{cancelToken: source.token});
// success
} catch (error) {
// fail
}