When using Axios for network requests, by default, Axios does not set a timeout, meaning the default timeout is 0. This implies that Axios requests will continue waiting for server responses indefinitely and will not automatically disconnect due to excessive time.
However, in practical applications, to prevent poor user experience or resource wastage caused by long waiting times, we typically set a reasonable timeout based on requirements.
For example, we can set the timeout in Axios's global configuration or in individual requests:
javascript// Set global timeout axios.defaults.timeout = 10000; // 10,000 milliseconds = 10 seconds // Or set timeout in individual requests axios.get('/user', { timeout: 5000 // 5,000 milliseconds = 5 seconds }) .then(response => { console.log(response); }) .catch(error => { if (error.code === 'ECONNABORTED') { console.log('Request timed out'); } else { console.log('Other error', error); } });
In the example above, I first set the global timeout to 10 seconds, meaning all requests without a specified timeout will time out after 10 seconds. I also demonstrated how to set a 5-second timeout for a specific request. This configuration can be flexibly adjusted based on the importance and expected response time of different requests. If a request does not receive a response within the set time, it will throw an error, which we can handle by catching this error to manage timeout scenarios.