This content originally appeared on DEV Community and was authored by Harsh Mishra
Introduction to Axios
Axios is a promise-based HTTP client for making HTTP requests in JavaScript. It allows you to send asynchronous HTTP requests to REST endpoints and handle responses in a simple, clean way. Axios works both in the browser and in Node.js, providing a unified way to interact with APIs.
Key Features of Axios:
-
Promise-based: Built on Promises, allowing easier asynchronous code management with
.then()
and.catch()
methods orasync/await
. - Supports all HTTP methods: GET, POST, PUT, PATCH, DELETE, etc.
-
Automatic JSON conversion: Automatically transforms JSON data, so you don’t need to handle
JSON.parse()
orJSON.stringify()
manually. - Client-side and server-side support: Works in both browser-based JavaScript environments and in Node.js.
Installation
There are two primary ways to install Axios:
1. Using npm (Node.js environment or modern JavaScript projects):
If you're using Node.js or working on a modern JavaScript project that uses npm, you can install Axios via npm:
npm install axios
2. Using CDN (For browser-based projects):
If you’re working on a browser-based project and don’t want to use npm, you can include Axios via a CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
This will allow you to use Axios directly in your HTML file without any additional setup.
Axios GET Request
Axios provides a straightforward way to make GET requests to retrieve data from APIs or web services. It supports various features like handling responses, setting custom headers, and adding query parameters. GET requests are typically used to fetch data from a server, and Axios simplifies this process by providing a clean API for making these requests and handling responses.
Syntax
axios.get(url[, config])
Parameters
-
url
:-
Type:
string
- Description: The URL to which the GET request is sent. This can be a full URL or a relative URL based on the base URL set in the Axios instance.
-
Type:
-
config
(optional):-
Type:
object
-
Description: An optional configuration object that can include various properties to customize the request. Key properties include:
-
params
: -
Type:
object
-
Description: An object representing query parameters to be appended to the URL. Example:
{ userId: 1, _limit: 5 }
. -
headers
: -
Type:
object
-
Description: Custom headers to include in the request. Example:
{ 'Authorization': 'Bearer token123' }
. -
timeout
: -
Type:
number
-
Description: Time in milliseconds before the request times out. Example:
5000
(5 seconds). -
responseType
: -
Type:
string
-
Description: The type of data expected from the server. Common values include
'json'
,'blob'
,'text'
. Example:'json'
.
-
-
Type:
Example Code
Here’s an example of a GET request using Axios with query parameters and custom headers:
const axios = require('axios');
axios.get('https://jsonplaceholder.typicode.com/posts', {
params: {
userId: 1, // Example query parameter
_limit: 5, // Example query parameter
_sort: 'date' // Example query parameter
},
headers: {
'Authorization': 'Bearer token123', // Example header
'Content-Type': 'application/json', // Example header
'Accept-Language': 'en-US' // Example header
},
timeout: 5000, // 5 seconds timeout
responseType: 'json' // Expected response type
})
.then(response => {
console.log(response.data); // Logs the response data
})
.catch(error => {
console.error('Error occurred:', error); // Handles error
});
Explanation:
-
params
: Includes query parameters to filter or sort the data. -
headers
: Sets custom headers for authorization and content type. -
timeout
: Specifies a timeout to avoid long-running requests. -
responseType
: Specifies that the response data should be in JSON format.
Axios POST Request
Axios simplifies making POST requests to send data to a server or API. POST requests are commonly used to submit data to be processed, such as creating a new resource or updating an existing one. Axios provides a clean and easy-to-use API for handling these requests.
Syntax
axios.post(url[, data[, config]])
Parameters
-
url
:-
Type:
string
- Description: The URL to which the POST request is sent. This can be a full URL or a relative URL based on the base URL set in the Axios instance.
-
Type:
-
data
:-
Type:
object
|string
- Description: The data to be sent as the request body. This can be an object, string, or any type of data you need to submit.
-
Type:
-
config
(optional):-
Type:
object
-
Description: An optional configuration object that can include various properties to customize the request. Key properties include:
-
params
: -
Type:
object
-
Description: An object representing query parameters to be appended to the URL. Example:
{ userId: 1 }
. -
headers
: -
Type:
object
-
Description: Custom headers to include in the request. Example:
{ 'Authorization': 'Bearer token123' }
. -
timeout
: -
Type:
number
-
Description: Time in milliseconds before the request times out. Example:
5000
(5 seconds). -
responseType
: -
Type:
string
-
Description: The type of data expected from the server. Common values include
'json'
,'blob'
,'text'
. Example:'json'
.
-
-
Type:
Example Code
Here’s an example of a POST request using Axios with a request body, query parameters, and custom headers:
const axios = require('axios');
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1
}, {
params: {
apiKey: 'your-api-key' // Example query parameter
},
headers: {
'Authorization': 'Bearer token123', // Example header
'Content-Type': 'application/json', // Example header
'Accept-Language': 'en-US' // Example header
},
timeout: 5000, // 5 seconds timeout
responseType: 'json' // Expected response type
})
.then(response => {
console.log(response.data); // Logs the response data
})
.catch(error => {
console.error('Error occurred:', error); // Handles error
});
Explanation:
-
data
: Contains the data to be sent in the request body. -
params
: Includes query parameters appended to the URL. -
headers
: Sets custom headers for authorization and content type. -
timeout
: Specifies a timeout to avoid long-running requests. -
responseType
: Specifies that the response data should be in JSON format.
Note: The usage of axios.put
, axios.patch
, and axios.delete
is similar to axios.post
. They allow you to send data (for put
and patch
) or just make requests with different HTTP methods.
Axios Response
When you make a request using Axios, the response object provides important details about the server’s response. This response object is structured and includes useful information such as the response data, status code, headers, and more. Understanding how to handle the response can help you work effectively with API responses, especially in error handling and logging.
Structure of Axios Response
The response object returned by Axios consists of the following key properties:
-
data
:-
Type:
object
|string
|array
|Buffer
-
Description: The actual data returned by the server. This can be an object, a string, or other data types, depending on the
responseType
set in the Axios configuration. Most often, it will be JSON data.
-
Type:
-
status
:-
Type:
number
-
Description: The HTTP status code of the response. Common status codes include:
-
200
: Success (OK) -
201
: Resource created -
400
: Bad request -
401
: Unauthorized -
404
: Not found -
500
: Internal server error
-
-
Type:
-
statusText
:-
Type:
string
-
Description: The status message corresponding to the HTTP status code (e.g., "OK" for
200
, "Not Found" for404
).
-
Type:
-
headers
:-
Type:
object
-
Description: The headers sent back by the server as part of the response. This object contains key-value pairs where the keys represent the header names and the values represent the header values. For example,
headers['content-type']
may be'application/json'
.
-
Type:
-
config
:-
Type:
object
- Description: The configuration object used to make the request. This includes details such as the URL, method, headers, and params.
-
Type:
-
request
:-
Type:
object
- Description: The original XMLHttpRequest (or Node.js HTTP request in server environments) used to make the request. This is primarily useful for debugging.
-
Type:
Example Code
Here’s an example of how to make a GET request and handle the response object in Axios:
const axios = require('axios');
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log('Data:', response.data); // Logs the response data (JSON)
console.log('Status Code:', response.status); // Logs the status code (200)
console.log('Status Text:', response.statusText);// Logs the status text (OK)
console.log('Headers:', response.headers); // Logs the response headers
console.log('Config:', response.config); // Logs the request configuration
})
.catch(error => {
console.error('Error:', error); // Handles any error that occurs during the request
});
Explanation:
-
data
: Retrieves the response data, which is likely a JSON object. -
status
: Retrieves the HTTP status code from the response. -
statusText
: Retrieves the text message associated with the status code. -
headers
: Retrieves the headers returned by the server. -
config
: Logs the configuration used for the request.
Handling Response in an Error Scenario
In case of an error (e.g., a request to an invalid URL or server error), Axios will throw an error. You can handle these errors in the .catch
block and inspect the response to get more information.
axios.get('https://jsonplaceholder.typicode.com/invalidurl')
.then(response => {
console.log(response.data);
})
.catch(error => {
if (error.response) {
console.log('Error Status:', error.response.status); // Logs error status code
console.log('Error Data:', error.response.data); // Logs error response data
console.log('Error Headers:', error.response.headers); // Logs error headers
} else if (error.request) {
console.log('No Response Received:', error.request); // Logs the request object if no response was received
} else {
console.log('Error Message:', error.message); // Logs any other error message
}
});
In this error-handling example:
-
error.response
: If the request was made but the server responded with a status other than2xx
,error.response
contains the full response object (withstatus
,data
,headers
, etc.). -
error.request
: If the request was made but no response was received,error.request
contains the original request object. -
error.message
: If something else went wrong, the error message will be logged.
This content originally appeared on DEV Community and was authored by Harsh Mishra
Harsh Mishra | Sciencx (2024-08-15T18:33:42+00:00) Axios Full Guide. Retrieved from https://www.scien.cx/2024/08/15/axios-full-guide/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.