What is Axios and why is it needed?
Axios is a powerful and popular JavaScript library for making HTTP requests. It works both in the browser and in the Node.js environment, providing a unified, convenient API based on Promise. If you need to send a GET request to an API, upload data to a server via POST, or process a response in JSON format, Axios will handle it elegantly and efficiently.
Why use Axios instead of the built-in fetch or XMLHttpRequest?
- Automatic JSON handling: Axios automatically transforms responses into JSON, eliminating the need to call
response.json(). - Interceptors: You can easily add global logic for all requests (e.g., authorization tokens) or responses (e.g., error handling).
- Request cancellation: Built-in support for canceling requests via
AbortController. - CSRF protection: Automatic work with XSRF tokens to enhance security.
- Upload progress: Ability to track the progress of sending and receiving data.
- Convenient error handling: More informative error messages and the ability to easily distinguish response statuses.
- Support for older browsers: Unlike
fetch, Axios works in Internet Explorer 11 and other legacy browsers.
Installation
Installing Axios in a Node.js project or frontend project (via npm/yarn/pnpm) is done with a single command:
# Installation via npm (recommended)npm install axios
# Installation via yarnyarn add axios
# Installation via pnpmpnpm add axiosFor use in the browser, you can also include Axios via CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>Quick Start
After installation, you can start making requests immediately. Here is a simple example of a GET request to a public API:
// Import the library (for Node.js or modular projects)import axios from 'axios';
// Make a GET request to the JSONPlaceholder APIaxios.get('https://jsonplaceholder.typicode.com/posts/1') .then(response => { console.log('Response status:', response.status); console.log('Data:', response.data); }) .catch(error => { console.error('Request error:', error.message); });This code will send a GET request, receive a response, and output its status and body (which is already automatically parsed from JSON into a JavaScript object).
Main Methods and Functions
Axios provides convenient wrapper methods for all major HTTP methods. Each of them returns a Promise.
1. axios.get(url, config?)
What it does: Performs an HTTP GET request to retrieve data from the server.
Parameters:
url(string) — The URL of the request.config(object, optional) — An Axios configuration object (e.g.,headers,paramsfor query string,timeout).
Example:
// Request with query parametersaxios.get('https://api.example.com/users', { params: { page: 2, limit: 10 }, headers: { 'Authorization': 'Bearer my-token' }}).then(response => { console.log(response.data);});2. axios.post(url, data?, config?)
What it does: Performs an HTTP POST request to send data to the server (usually to create a new resource).