HTTP requests using Axios
By Flavio Copes
Learn how to make HTTP requests with Axios, pass query parameters, send JSON, handle errors, set timeouts, and cancel requests.
Axios is a promise-based HTTP client for browsers and Node.js. It provides one API for sending requests, transforming JSON, handling errors, setting timeouts, and cancelling work.
Modern JavaScript also has the built-in Fetch API. Axios is useful when you prefer its request configuration, automatic JSON handling, interceptors, or its default rejection of responses outside the 2xx range.
Install Axios
Install the package:
npm install axios
Then import it:
import axios from 'axios'
You can also load Axios in a browser with the CDN script shown in the official installation guide.
Send a GET request
Call axios.get() and await the response:
import axios from 'axios'
const response = await axios.get('https://api.example.com/users/42')
console.log(response.data)
console.log(response.status)
console.log(response.headers)
Axios puts the parsed response body in response.data. JSON responses are parsed automatically.
Add query parameters
Use the params option instead of assembling the URL by hand:
const response = await axios.get('https://api.example.com/users', {
params: {
role: 'admin',
page: 2,
},
})
Axios serializes those values into a URL such as:
https://api.example.com/users?role=admin&page=2
Send JSON with POST
Pass the request body as the second argument:
const response = await axios.post('https://api.example.com/users', {
name: 'Roger',
email: 'roger@example.com',
})
console.log(response.data)
Axios serializes the object as JSON and sets the appropriate request header.
For methods that take a body, the general signature is:
axios({
method: 'put',
url: 'https://api.example.com/users/42',
data: {
name: 'Roger',
},
})
Set a timeout
A timeout prevents a request from waiting forever:
const response = await axios.get('https://api.example.com/reports', {
timeout: 5000,
})
The timeout is expressed in milliseconds. The default is 0, which means no timeout.
Choose a value that makes sense for the operation. A report export can reasonably take longer than an autocomplete request.
Cancel a request
Axios supports the standard AbortController API:
const controller = new AbortController()
const request = axios.get('https://api.example.com/search', {
signal: controller.signal,
})
controller.abort()
try {
await request
} catch (error) {
if (axios.isCancel(error)) {
console.log('Request cancelled')
}
}
The older Axios CancelToken API is deprecated. Use AbortController in new code.
Handle errors
Axios rejects the promise when the response status falls outside the configured success range:
try {
const response = await axios.get('https://api.example.com/users/42')
console.log(response.data)
} catch (error) {
if (axios.isAxiosError(error)) {
if (error.response) {
console.error('Server responded with:', error.response.status)
console.error(error.response.data)
} else if (error.request) {
console.error('No response received')
} else {
console.error(error.message)
}
} else {
throw error
}
}
error.response means the server replied with an unsuccessful status. error.request means the request was sent but no response was received.
Do not show raw server error data to users without checking it first.
Create an Axios instance
For a larger application, create an instance with shared defaults:
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: {
accept: 'application/json',
},
})
const response = await api.get('/users/42')
Instances can also have request and response interceptors. They are useful for consistent authentication and error handling, but keep them small: hidden global behavior can make requests harder to debug.
CORS, credentials, and XSRF
Axios does not bypass browser security rules. Cross-origin browser requests still need the server to return the correct CORS headers.
To include cookies in a cross-origin request, both the client and server must be configured for credentials:
await axios.get('https://api.example.com/account', {
withCredentials: true,
})
Axios has browser options for reading an XSRF token from a cookie and sending it in a header. Those options only help when your server issues and validates that token. Axios cannot make an endpoint secure by itself.
See the official Axios documentation for the complete request configuration, response schema, error handling, and request cancellation.
Related posts about node: