Setting Timeout in Axios Requests
Introduction
Axios is a popular JavaScript library used for making HTTP requests in web applications. It provides a variety of features to handle timeouts when sending requests.
Options for Setting Timeouts
There are several ways to set a timeout in Axios:
1. Request Configuration Object
By setting the `timeout` property in the configuration object when creating a request. For example: ```javascript const axios = require('axios'); const config = { timeout: 5000 // Abort request after 5 seconds }; axios.get('/api/data', config); ```
2. Instance Level
By setting the `timeout` property when creating an instance of Axios. This will apply the timeout to all requests made through that instance: ```javascript const axios = require('axios'); const instance = axios.create({ timeout: 5000 }); instance.get('/api/data'); ```
3. Interceptors
Axios interceptors allow setting a timeout for each request and handling timeouts in response interceptors. For example: ```javascript const axios = require('axios'); axios.interceptors.request.use((config) => { config.timeout = 5000; return config; }); ``` When using the above method, a timeout can be set for each request individually by modifying the configuration object before sending the request. By understanding these options, developers can effectively handle timeouts when using Axios, ensuring that requests are handled promptly and appropriately.
Komentar