How to Handle HTTP Post Request in Node Js Application

How to Handle HTTP Post Request in Node Js App

HTTP requests help you communicate with the server and help you manage the data pretty quickly.

In Node, you can make HTTP requests to send and receive the data. Node has its own way of dealing with HTTP requests.

In this quick guide, we will demonstrate how to handle HTTP post requests using the request package’s post method in the Node js application.

The HTTP Post method is used to send the data on the server in the json format through the post request param.

This guide is meant to create newbie developers in mind. So, before we call the HTTP post request in Node, we will show you the complete process of setting up a basic node app.

Moreover, we will teach you how to use json-server in Node to build a fake server that gives us demo Post API.

At the end of this guide, you will know how to create post API, call HTTP post request in Node, and receive post request response in the body.

Node JS HTTP POST Request Tutorial

  • Step 1: Build Node Project
  • Step 2: Install Request Package
  • Step 3: Create Fake API
  • Step 4: Handle Http Request
  • Step 5: Update Package Json
  • Step 6: Test Http Request

Build Node Project

You must have a project folder where you will be writing logic to build your node app. Here is the command that will create the project folder.

mkdir node-loop

After the folder is created, moved inside this directory.

cd node-loop

Now, type the following command on the terminal and execute the command.

npm init

Npm command generates the new package.json file; this file contains the scripts, command, and other essential information about your node app.

Install Request Package

In the following step, we will have to install the request library in the node app. Here is the command that will help you add the package.

npm install request

Create Fake API

HTTP Requests are made with APIs; setting up API requires an extensive backend.

In this section, we will demystify you how to set up a fake API through a mock server using the json-server package.

Below is the command you have to invoke to install the json-server package.

npm install json-server

Now, create the sample file in your node project, name the file db.json and pour the following data into the file.

{
  "users": [
    {
      "id": "",
      "firstName": "",
      "lastName": "",
      "email": "",
      "profile": ""
    }
  ]
}

Let us start the json server and manifest the API urls on the terminal screen.

json-server --watch db.json

You will see something similar to this:

\{^_^}/ hi!

  Loading db.json
  Done

  Resources
  http://localhost:3000/users

  Home
  http://localhost:3000

Handle Http Request

A node application must have a main app.js file; this file holds the primary code of the app.

In this file, you have to import the request module, access the request.post() method.

It takes post request data as a first parameter and returns three values, error, res, and body. On the successful API call, we show the response on the terminal window.

Create the app.js file and insert the offered code in the file.

const request = require('request');
  
const postReq = {
    url: 'http://localhost:3000/users',
    json: true,
    body: {
        firstName: 'John',
        lastName: 'Doe',
        email: 'john@peculiar.com',
        profile: 'Physicist'
    }
};
   
request.post(postReq, (err, res, body) => {
    if (err) {
        return console.log(err);
    }

    console.log(body);
    console.log(`You have successfully made the post request`);
});

Update Package.json File

In this step, you will be updating the package.json file. It is necessary to make the node command work.

Consequently, go to the app.js file and add the main server file in the script tag.

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.js"
  },

Test Http Request

So far, every file has been created and placed the code appropriately.

Now, you need to test the post HTTP method and invoke the given command from the command line tool.

node app.js

We have made the http request and you can see the output:

{
  firstName: 'John',
  lastName: 'Doe',
  email: 'john@peculiar.com',
  profile: 'Physicist',
  id: 'fghSqf6'
}

Summary

This node post request example is just the beginning. It just gives you a basic idea about how HTTP requests are handled in the node app. However, this concept is not limited to this outlook.

As you start more working on real-world apps, you will see more advanced ways to handle HTTP post requests in node. However, it is apparent that this guide will give you a basic idea of its working paradigm.