Axios is the most popular HTTP client for JavaScript with 100M+ weekly downloads. It works in browsers and Node.js, with interceptors, automatic transforms, and cancellation support.
Installation
npm install axios
Basic Requests
import axios from "axios";
// GET
const { data } = await axios.get("https://api.github.com/users/axios");
console.log(data.name);
// POST
const response = await axios.post("https://httpbin.org/post", {
name: "Axios",
type: "http-client"
});
// With config
const result = await axios({
method: "put",
url: "https://api.example.com/users/1",
data: { name: "Updated" },
headers: { "Authorization": "Bearer token" },
timeout: 5000
});
Create Instance
const api = axios.create({
baseURL: "https://api.example.com/v2",
timeout: 10000,
headers: { "Authorization": "Bearer token" }
});
const users = await api.get("/users");
const user = await api.post("/users", { name: "New User" });
Interceptors
// Request interceptor — add auth token
api.interceptors.request.use((config) => {
const token = getAuthToken();
if (token) config.headers.Authorization = `Bearer ${token}`;
config.metadata = { startTime: Date.now() };
return config;
});
// Response interceptor — handle errors globally
api.interceptors.response.use(
(response) => {
const duration = Date.now() - response.config.metadata.startTime;
console.log(`${response.config.url}: ${duration}ms`);
return response;
},
async (error) => {
if (error.response?.status === 401) {
const newToken = await refreshToken();
error.config.headers.Authorization = `Bearer ${newToken}`;
return api(error.config); // Retry
}
return Promise.reject(error);
}
);
Concurrent Requests
const [users, posts, comments] = await Promise.all([
api.get("/users"),
api.get("/posts"),
api.get("/comments")
]);
File Upload with Progress
const formData = new FormData();
formData.append("file", fileInput.files[0]);
const response = await axios.post("/upload", formData, {
onUploadProgress: (progressEvent) => {
const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
console.log(`Upload: ${percent}%`);
}
});
Cancellation
const controller = new AbortController();
const promise = axios.get("/slow-api", { signal: controller.signal });
setTimeout(() => controller.abort(), 5000);
try {
const { data } = await promise;
} catch (err) {
if (axios.isCancel(err)) console.log("Request cancelled");
}
Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.
Top comments (0)