How to make HTTP POST request in Node.js

Hello programmers, In this article I will be explaining how we can make an HTTP POST request in Node.js.

HTTP requests are used to send/receive data by server and client. There are different types of HTTP requests for the same – (GET, POST, PUT, DELETE, etc..).  There are many ways to do so with several open-source libraries available with the node package manager. We can do this without installing any 3rd party dependency as well. To do so we can use the Native HTTPS module. But here we are going to use a third-party library called Axios. It is a promised-based request library that is used to perform HTTP requests. It has the upper hand over the native HTTPS module in many ways. Few are discussed below.

  1. Automatic conversion of response data to JSON.
  2. Better error handling over HTTPS module.
  3. It can monitor POST request progress.
  4. A wider range of browser compatibility

Let’s get started with our topic. First, initialize a new Node.js project by writing npm init to the terminal. After you are done with initializing the same install Axios by running the following code in the terminal.

npm install axios

Now we have our dependency installed. Goto the root file of the project and require the same. After that write the syntax for making a POST request.

//requiring the axios package
const axios = require('axios');

// It is just a dummy data.
const data = {
    name: 'Pikachu',
    type: 'Electric'
};

//URL is placeholder for api endpoint where you want to post data.
axios.post('URL', data)
    .then((res) => {
        console.log(res.data);
    }).catch((err) => {
        console.error(err);
    });

I hope this tutorial was a great read for you.

You may also learn,

Leave a Reply

Your email address will not be published.