HTTP Requests in Axios Nodejs: A Practical Guide

Node.js developers often rely on the built-in HTTP module to create or consume RESTful services. However, dealing with raw HTTP requests can be cumbersome and verbose. Enter Axios, a promise-based HTTP client that simplifies the process, making it more readable and efficient. This blog post will walk you through various examples of how Axios nodejs can handle all your HTTP needs with ease.

Why Axios?

Axios has become the go-to library for making HTTP requests in Node.js due to its simplicity and feature-rich interface. Unlike the standard HTTP library, Axios provides a promise-based approach, allowing you to write cleaner and more manageable asynchronous code. It supports interceptors that let you transform requests and responses at will, and it automatically transforms JSON data, saving you from manual parsing. Additionally, Axios is client-agnostic, functioning in both Node.js and browser environments, which is great for isomorphic code.

How to install axios?

To begin using Axios in your Node.js project, installation is just a command away. With npm, you would run

npm install axios,

or with Yarn,

yarn add axios.

Once installed, including Axios in your project is as simple as requiring the module:

const axios = require('axios');

With Axios now part of your project, you’re ready to make your first request.

Performing a GET Request

Retrieving data with Axios is straightforward. Here’s how to perform a GET request to fetch data from a placeholder API:

Example 1: Get request without query param

const fetchUsers = async () => {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/users');
    console.log(response.data);
  } catch (error) {
    console.error('Error fetching users:', error);
  }
};

fetchUsers();

Example 2: Get request with query param

const fetchUsers = async () => {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/users?p=becomegeeks');
    console.log(response.data);
  } catch (error) {
    console.error('Error fetching users:', error);
  }
};

fetchUsers();

Example 3: Simplified Get request with query param

To include query parameters, Axios simplifies the process, allowing you to pass an options object:

axios.get('https://jsonplaceholder.typicode.com/users', {
  params: {
    limit: 5
  }
});

Creating Data with POST Requests

Creating resources via POST requests with Axios is equally intuitive. You can send data to your server or any external service as JSON:

const createUser = async () => {
  try {
    const res = await axios.post('https://jsonplaceholder.typicode.com/users', {
      name: 'New User',
      email: 'newuser@example.com'
    });
    console.log('User created:', res.data);
  } catch (error) {
    console.error('Error creating user:', error);
  }
};

createUser();

Handling Form Data with POST Requests

Sometimes, you need to send data as application/x-www-form-urlencoded. Axios can handle this with the help of the qs library:

const qs = require('qs');
const createFormUser = async () => {
  try {
    const res = await axios.post('https://jsonplaceholder.typicode.com/users', qs.stringify({
      name: 'Form User',
      email: 'formuser@example.com'
    }), {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });
    console.log('Form user created:', res.data);
  } catch (error) {
    console.error('Error creating form user:', error);
  }
};

createFormUser();

Updating Data with PUT Requests

To update existing data, PUT requests are the standard. Here’s how you might update a user’s email:

const updateUser = async () => {
  try {
    const res = await axios.put('https://jsonplaceholder.typicode.com/users/1', {
      email: 'updateduser@example.com'
    });
    console.log('User updated:', res.data);
  } catch (error) {
    console.error('Error updating user:', error);
  }
};

updateUser();

Cleaning Up with DELETE Requests

Deleting a resource is as easy as calling axios.delete with the appropriate URL:

const deleteUser = async () => {
  try {
    await axios.delete('https://jsonplaceholder.typicode.com/users/1');
    console.log('User deleted');
  } catch (error) {
    console.error('Error deleting user:', error);
  }
};

deleteUser();

Best Practices and Error Handling

When working with Axios, it’s important to handle errors gracefully using try/catch blocks. Setting up interceptors for common pre-request or post-response actions, like adding authentication tokens, can also streamline your code. Configuring global defaults for headers, timeouts, and the base URL can save time and prevent repetition. Here are some examples for how to use axios nodejs error handling.

Error Handling:

Always use try/catch blocks when dealing with promises or async/await. Axios provides detailed errors, and you should log them or handle them appropriately.

try {
  const response = await axios.get('/user/12345');
  // Handle success
} catch (error) {
  // Handle error
  console.log(error);
}

Interceptors:

Utilize Axios interceptors to manage request and response handling globally. This is useful for logging, authentication, or any repetitive task for every request/response.

axios.interceptors.request.use(request => {
  // Edit request config, add headers, etc.
  return request;
}, error => {
  // Handle request error
  return Promise.reject(error);
});

Timeouts:

Set timeout in Axios config to prevent requests from hanging indefinitely. It’s a good practice to define a timeout for all HTTP requests.

axios.get('/user/12345', { timeout: 10000 });

Cancel Token:

Use Axios’s CancelToken to cancel requests to avoid memory leaks and unwanted responses if the component is unmounted or the request is no longer needed.

const { CancelToken } = axios;
const source = CancelToken.source();

axios.get('/user/12345', { cancelToken: source.token });

// Cancel the request if needed
source.cancel('Operation canceled by the user.');

Axios nodejs provides a robust solution for managing HTTP requests in Node.js applications. With its easy-to-understand syntax and comprehensive feature set, it streamlines interactions with APIs and external services.

More examples for axios nodejs post with headers and body with examples