You are currently viewing Making HTTP POST Requests with Axios

Making HTTP POST Requests with Axios

When developing web applications, interacting with APIs to send data is a crucial task. HTTP POST requests are commonly used for this purpose, allowing you to submit data to be processed by a server. POST requests are integral to many functionalities, such as submitting forms, uploading files, and creating new resources.

Axios, a popular JavaScript library, simplifies the process of making HTTP POST requests by providing a promise-based interface. This makes it easy to handle asynchronous operations in JavaScript. In this comprehensive guide, we’ll explore how to use Axios to make POST requests, handle responses and errors, and configure requests to suit different use cases.

Understanding HTTP POST Requests

An HTTP POST request is a method used to send data to a server to create or update a resource. When a POST request is made, the server processes the data sent in the body of the request and returns a response. Unlike GET requests, POST requests can send large amounts of data, including binary data, in a secure manner.

Use Cases for POST Requests

POST requests are used in various scenarios, such as:

  • Submitting Forms: Sending form data to a server for processing.
  • Uploading Files: Uploading files such as images or documents.
  • Creating Resources: Creating new resources in a database, such as adding a new user or product.
  • Authentication: Sending login credentials to a server for authentication.

Setting Up Axios in Your Project

To start using Axios for making POST requests, you need to set it up in your project. You can install Axios via npm/yarn or include it via a CDN.

Installing Axios via npm/yarn

If you’re using npm or yarn, you can install Axios with a simple command.

Using npm:

npm install axios

Using yarn:

yarn add axios

After installation, you can import Axios in your JavaScript files:

import axios from 'axios';

Setting Up Axios via CDN

If you prefer to include Axios via a Content Delivery Network (CDN), you can add the following script tag to your HTML file:

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

This approach is useful for quick setups or for use in environments where a package manager is not available. When included via CDN, Axios is available globally as axios.

Making Simple POST Requests

Once Axios is set up in your project, making a POST request is straightforward. Here is a basic example.

Using npm/yarn:

import axios from 'axios';

// Function to send data to an API
const postData = async () => {

  try {
  
    const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
      title: 'foo',
      body: 'bar',
      userId: 1
    });
	
    console.log('Response data:', response.data);
	
  } catch (error) {
    console.error('Error posting data:', error);
  }
};

// Call the function to send data
postData();

Using CDN:

<script>

  // Function to send data to an API
  const postData = async () => {
  
    try {
	
      const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
        title: 'foo',
        body: 'bar',
        userId: 1
      });
	  
      console.log('Response data:', response.data);
	  
    } catch (error) {
      console.error('Error posting data:', error);
    }
	
  };

  // Call the function to send data
  postData();
  
</script>

In this example, we define a function postData that sends a POST request to the URL https://jsonplaceholder.typicode.com/posts with a JSON payload containing title, body, and userId fields. The axios.post method is used to send the POST request. The first argument is the URL endpoint, and the second argument is the data payload to be sent. The await keyword ensures that the function waits for the request to complete before continuing. The response data is logged to the console if the request is successful, and any errors are caught and logged.

Handling Responses and Errors

When you make a request with Axios, the response object contains several properties, including data, status, statusText, headers, and config. These properties provide detailed information about the response, allowing you to handle it appropriately.

Here’s an example of how to handle responses and errors in Axios:

Using npm/yarn:

import axios from 'axios';

// Function to send data and handle responses and errors
const postData = async () => {

  try {
  
    const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
      title: 'foo',
      body: 'bar',
      userId: 1
    });
	
    console.log('Data:', response.data);
    console.log('Status:', response.status);
	
  } catch (error) {
  
    if (error.response) {
	
      // Server responded with a status other than 2xx
      console.error('Error response data:', error.response.data);
      console.error('Error response status:', error.response.status);
	  
    } else if (error.request) {
	
      // No response received from server
      console.error('Error request:', error.request);
	  
    } else {
	
      // Other errors
      console.error('Error message:', error.message);
	  
    }
	
  }
  
};

// Call the function to send data
postData();

Using CDN:

<script>

  // Function to send data and handle responses and errors
  const postData = async () => {
  
    try {
	
      const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
        title: 'foo',
        body: 'bar',
        userId: 1
      });
	  
      console.log('Data:', response.data);
      console.log('Status:', response.status);
	  
    } catch (error) {
	
      if (error.response) {
	  
        // Server responded with a status other than 2xx
        console.error('Error response data:', error.response.data);
        console.error('Error response status:', error.response.status);
		
      } else if (error.request) {
	  
        // No response received from server
        console.error('Error request:', error.request);
		
      } else {
	  
        // Other errors
        console.error('Error message:', error.message);
		
      }
	  
    }
	
  };

  // Call the function to send data
  postData();
  
</script>

In this example, we extend the postData function to handle different types of errors. The axios.post method is used to make the request, and the response data and status are logged to the console if successful.

The catch block differentiates between three types of errors:

  • Error response: The server responded with a status code other than 2xx.
  • Error request: The request was made, but no response was received.
  • Other errors: Any other errors that might occur, such as network issues.

By handling these different error scenarios, you can ensure that your application responds appropriately to various error conditions.

Configuring POST Requests

In many cases, you need to configure your POST requests with custom headers and additional data. Axios allows you to easily add these configurations to your requests.

Using npm/yarn:

import axios from 'axios';

// Function to send data with custom headers
const postData = async () => {

  try {
  
    const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
      title: 'foo',
      body: 'bar',
      userId: 1
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer token'
      }
    });
	
    console.log('Response data:', response.data);
	
  } catch (error) {
    console.error('Error posting data:', error);
  }
  
};

// Call the function to send data
postData();

Using CDN:

<script>

  // Function to send data with custom headers
  const postData = async () => {
  
    try {
	
      const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
        title: 'foo',
        body: 'bar',
        userId: 1
      }, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer token'
        }
      });
	  
      console.log('Response data:', response.data);
	  
    } catch (error) {
      console.error('Error posting data:', error);
    }
	
  };

  // Call the function to send data
  postData();
  
</script>

In this example, we define a function postData that sends a POST request to the URL https://jsonplaceholder.typicode.com/posts with a JSON payload containing title, body, and userId fields. Additionally, custom headers are added using the headers option. The Content-Type header is set to application/json to specify the format of the data being sent, and the Authorization header is set to a bearer token for authentication purposes. The response data is logged to the console if the request is successful, and any errors are caught and logged.

Advanced Usage of POST Requests

Using Axios Interceptors

Interceptors allow you to run your code or modify the request or response before they are handled by then or catch. This is useful for tasks like adding authorization tokens to requests or logging request and response details.

Using npm/yarn:

import axios from 'axios';

// Add a request interceptor
axios.interceptors.request.use(

  config => {
    console.log('Request made with ', config);
    config.headers.Authorization = 'Bearer token';
    return config;
  },
  
  error => {
    return Promise.reject(error);
  }
  
);

// Add a response interceptor
axios.interceptors.response.use(

  response => {
    console.log('Response received', response);
    return response;
  },
  
  error => {
    console.log('Error response', error.response);
    return Promise.reject(error);
  }
  
);

// Function to make a request
const postData = async () => {

  try {
  
    const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
      title: 'foo',
      body: 'bar',
      userId: 1
    });
	
    console.log('Response data:', response.data);
	
  } catch (error) {
    console.error('Error posting data:', error);
  }
  
};

// Call the function to send data
postData();

Using CDN:

<script>

  // Add a request interceptor
  axios.interceptors.request.use(
  
    config => {
      console.log('Request made with ', config);
      config.headers.Authorization = 'Bearer token';
      return config;
    },
	
    error => {
      return Promise.reject(error);
    }
	
  );

  // Add a response interceptor
  axios.interceptors.response.use(
  
    response => {
      console.log('Response received', response);
      return response;
    },
	
    error => {
      console.log('Error response', error.response);
      return Promise.reject(error);
    }
	
  );

  // Function to make a request
  const postData = async () => {
  
    try {
	
      const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
        title: 'foo',
        body: 'bar',
        userId: 1
      });
	  
      console.log('Response data:', response.data);
	  
    } catch (error) {
      console.error('Error posting data:', error);
    }
	
  };

  // Call the function to send data
  postData();
  
</script>

In this example, we add request and response interceptors using axios.interceptors.request.use and axios.interceptors.response.use methods. The request interceptor logs the request configuration and adds an authorization header. The response interceptor logs the response details and handles errors. By using interceptors, you can centralize and streamline request and response handling logic, making your code cleaner and more maintainable.

Conclusion

In this article, we explored how to make HTTP POST requests using Axios. We covered the basics of setting up Axios, making simple POST requests, handling responses and errors, configuring POST requests with headers and additional data, and using interceptors for advanced request handling.

The examples and concepts discussed provide a solid foundation for working with Axios in your projects. However, there is much more to explore. I encourage you to experiment further with Axios, integrating it into your applications to handle API interactions efficiently and effectively.

Leave a Reply