HTTP Requests in JavaScript with Axios
Axios is a popular promise-based HTTP client for browsers and Node.js. It provides a compact API for requests, JSON handling, interceptors, timeouts, custom instances, and request cancellation.
This guide uses the DummyJSON API to demonstrate common CRUD-style requests.
1. Install Axios
With npm:
npm install axiosFor a simple browser page, you can also load a CDN build:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>2. Fetch All Products
axios.get('https://dummyjson.com/products')
.then((response) => console.log(response.data))
.catch((error) => console.error('Error:', error));3. Fetch a Product by ID
axios.get('https://dummyjson.com/products/1')
.then((response) => console.log(response.data))
.catch((error) => console.error('Error:', error));4. Search Products
Use params instead of manually assembling query strings:
axios.get('https://dummyjson.com/products/search', {
params: { q: 'phone' },
})
.then((response) => console.log(response.data))
.catch((error) => console.error('Error:', error));5. Create a Product
axios.post('https://dummyjson.com/products/add', {
title: 'BMW Pencil',
})
.then((response) => console.log(response.data))
.catch((error) => console.error('Error:', error));6. Update a Product
axios.put('https://dummyjson.com/products/1', {
title: 'Updated Product',
})
.then((response) => console.log(response.data))
.catch((error) => console.error('Error:', error));7. Delete a Product
axios.delete('https://dummyjson.com/products/1')
.then((response) => console.log(response.data))
.catch((error) => console.error('Error:', error));DummyJSON simulates write operations; it does not persist these changes as a real production database would.
8. Create a Reusable Axios Instance
// api.js
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://dummyjson.com/',
timeout: 5000,
});
export const api = {
getProducts: () => apiClient.get('products'),
getProduct: (id) => apiClient.get(`products/${id}`),
searchProducts: (q) => apiClient.get('products/search', { params: { q } }),
addProduct: (product) => apiClient.post('products/add', product),
updateProduct: (id, product) => apiClient.put(`products/${id}`, product),
deleteProduct: (id) => apiClient.delete(`products/${id}`),
};Then use the module elsewhere:
import { api } from './api.js';
const response = await api.getProducts();
console.log(response.data);9. Prefer async/await for Multi-Step Logic
Promises with .then() are valid, but async/await is often easier to read when requests are part of larger workflows:
async function loadProducts() {
try {
const response = await api.getProducts();
return response.data.products;
} catch (error) {
if (axios.isAxiosError(error)) {
console.error('Request failed:', error.response?.status, error.message);
} else {
console.error('Unexpected error:', error);
}
throw error;
}
}10. Interceptors and Authentication
Interceptors can apply shared logic to every request:
apiClient.interceptors.request.use((config) => {
const token = getAccessToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});Avoid logging secrets or blindly attaching credentials to third-party origins.
Conclusion
Axios provides a practical abstraction for HTTP requests when you want features beyond the browser’s built-in fetch, such as reusable instances, interceptors, consistent error objects, and simple timeouts. Keep request logic centralized, handle failures deliberately, and treat authentication headers and API data as security-sensitive.