Create new axios nstance
To create a new Axios instance, you can use the following syntax:
import axios from 'axios';
const instance = axios.create({
// options
});
The axios.create()
method returns a new Axios instance with the options you provide.
Here are some common options you can pass to axios.create()
:
baseURL
: The base URL for the instance. Axios will prefix all requests with this URL.timeout
: The timeout in milliseconds for the instance.headers
: The default headers for the instance.paramsSerializer
: A function that serializes the request parameters.transformRequest
: A function that transforms the request data.transformResponse
: A function that transforms the response data.maxContentLength
: The maximum allowed content length in bytes.maxBodyLength
: The maximum allowed body length in bytes.validateStatus
: A function that validates the response status code.
Here's an example of creating a new Axios instance with some options:
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
}
});
You can then use this instance to make requests:
instance.get('/users')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
Note that you can also pass options to individual requests using the axios
instance. For example:
instance.get('/users', {
timeout: 5000,
headers: {
'X-Custom-Header': 'custom-value'
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
This way, you can override the default options for a specific request.