Making HTTP Requests in JavaScript with Axios

3 min read .

Axios is a popular JavaScript library that makes it easy to send HTTP requests. It’s widely used for making API calls and handling responses in web applications. In this guide, we’ll explore how to use Axios to perform various CRUD (Create, Read, Update, Delete) operations using examples from the DummyJSON API.

1. Introduction to Axios

Axios is a promise-based HTTP client for JavaScript that provides a simpler and cleaner syntax than the native Fetch API. It’s particularly well-suited for handling complex HTTP requests, making it a popular choice among developers.

To get started, install Axios using npm:

npm install axios

Or include it via a CDN in your HTML file:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

2. Fetching All Products

To fetch a list of all products from the DummyJSON API, use the following code:

axios.get('https://dummyjson.com/products')
  .then(response => console.log(response.data))
  .catch(error => console.error('Error fetching products:', error));

This code sends a GET request to the /products endpoint, retrieves the response, and logs the product data to the console.

3. Fetching a Single Product by ID

To fetch a specific product by its ID, use the product ID in the URL:

axios.get('https://dummyjson.com/products/1')
  .then(response => console.log(response.data))
  .catch(error => console.error('Error fetching product:', error));

This example retrieves the product with ID 1 and logs its details.

4. Searching for Products

To search for products that match a specific query, such as “phone,” use the following code:

axios.get('https://dummyjson.com/products/search?q=phone')
  .then(response => console.log(response.data))
  .catch(error => console.error('Error searching products:', error));

This request returns a list of products that match the search query “phone.”

5. Adding a New Product

To add a new product to the DummyJSON database, use a POST request:

axios.post('https://dummyjson.com/products/add', {
  title: 'BMW Pencil',
  /* other product data */
})
  .then(response => console.log(response.data))
  .catch(error => console.error('Error adding product:', error));

This code adds a new product with the title “BMW Pencil” to the database and logs the response.

6. Updating a Product

To update an existing product, such as changing its title, use a PUT request:

axios.put('https://dummyjson.com/products/1', {
  title: 'iPhone Galaxy +1'
})
  .then(response => console.log(response.data))
  .catch(error => console.error('Error updating product:', error));

This code updates the title of the product with ID 1 to “iPhone Galaxy +1.”

7. Deleting a Product

To delete a product from the database, use a DELETE request:

axios.delete('https://dummyjson.com/products/1')
  .then(response => console.log(response.data))
  .catch(error => console.error('Error deleting product:', error));

This request deletes the product with ID 1, and the response is logged to confirm the deletion.

8. Creating a Module with Axios

To organize your Axios requests, you can create a module. Here’s a simple example:

// api.js
import axios from 'axios';

const apiClient = axios.create({
  baseURL: 'https://dummyjson.com/',
  headers: {
    'Content-Type': 'application/json'
  }
});

export default {
  getProducts() {
    return apiClient.get('products');
  },
  getProduct(id) {
    return apiClient.get(`products/${id}`);
  },
  searchProducts(query) {
    return apiClient.get(`products/search`, { params: { q: query } });
  },
  addProduct(product) {
    return apiClient.post('products/add', product);
  },
  updateProduct(id, product) {
    return apiClient.put(`products/${id}`, product);
  },
  deleteProduct(id) {
    return apiClient.delete(`products/${id}`);
  }
};

You can then import this module into your main code and use it like this:

import api from './api.js';

api.getProducts().then(response => console.log(response.data));

This approach keeps your HTTP requests organized and reusable throughout your application.

9. Best Practices for Using Axios

  • Error Handling: Always include .catch() for handling errors, especially for production code.

  • Interceptors: Use Axios interceptors to manage request and response transformations globally, such as adding authentication tokens.

  • Timeouts: Set timeouts for your requests to handle scenarios where the server is unresponsive.

    const apiClient = axios.create({
      baseURL: 'https://dummyjson.com/',
      timeout: 5000, // 5 seconds
    });

Conclusion

Axios simplifies the process of making HTTP requests in JavaScript, offering a clean and intuitive API for performing CRUD operations. Whether you’re working with RESTful APIs or need advanced request configurations, Axios is a powerful tool that can help streamline your development process.

See Also

chevron-up