Handling POST requests in Express.js

  • Post category:Express
  • Reading time:4 mins read

In this post, we will learn how to handle POST requests in Node.js.

How to handle POST requests in Node.js?

Now, let’s look at an example of POST requests in Node.js, and then I will explain this code.

Folder structure:



// app.js
const fs = require("fs");
const express = require("express");
const app = express();

const countriesData = JSON.parse(

app.post("/hello", (req, res) => {
  console.log("req.body", req.body);
  let id = countriesData.length + 1;
  let requestData = Object.assign({ id: id.toString() }, req.body);
  let updatedData = JSON.stringify(countriesData);
  fs.writeFile(`${__dirname}/data/data.json`, updatedData, (err) => {
    if (err) {
      return res.status(500).json({
        status: "error",
        message: "Failed to write data",
      status: "success",
      data: requestData,

const port = 8000;
app.listen(port, () => {
  console.log(`current port: ${port}`);


  { "id": "1", "country": "India", "cities": ["Delhi", "Mumbai"] },
  { "id": "2", "country": "China", "cities": ["Shanghai", "Beijing"] },
  { "id": "3", "country": "USA", "cities": ["New York", "Los Angeles"] },
  { "id": "4", "country": "Japan", "cities": ["Tokyo", "Kyoto"] }

API Response using Postman

how to handle post api

Type the API URL in Postman. Then go to the body and type the params. In the above image, you can see that I have passed country and cities as params. Don’t forget to select raw and JSON (see the image below). Now, hit the send button, and the API will give you the response.

Updated data.json file:

This is the updated list from data.json when I hit the above API URL (i.e., ‘/hello’).

  { "id": "1", "country": "India", "cities": ["Delhi", "Mumbai"] },
  { "id": "2", "country": "China", "cities": ["Shanghai", "Beijing"] },
  { "id": "3", "country": "USA", "cities": ["New York", "Los Angeles"] },
  { "id": "4", "country": "Japan", "cities": ["Tokyo", "Kyoto"] },
  { "id": "5", "country": "Australia", "cities": ["Sydney", "Melbourne"] }

Code Explanation:

  • In app.js, I have imported all the required modules.
  • By writing app.use(express.json()); I created the middleware, which parses incoming JSON requests and makes the request body available in the req.body.
  • On line number 7, JSON.parse converts the file content from JSON string to a JavaScript object, and fs.readFileSync(`${__dirname}/data/data.json`) synchronously reads the content of the file data.json.
  • On line number 11, app.post(“/hello”, (req, res) => { … }); this code defines a route that handles POST requests to /hello.
  • Line 13: this code generates a new ID by incrementing the length of countriesData by 1. So, whenever I hit the ‘/hello‘ API URL, a new ID will create a new record, as you can see in the updated data.json file above.
  • Line number 14: It creates a new object that combines the generated ID with the incoming request body. So whenever I send any data from the post API, I will receive that data in the request.
  • Line number 15: It adds the new data to the countriesData array.
  • Line number 16: It converts the updated countriesData array back to a JSON string.
  • Line number 17: fs.writeFile Asynchronously writes the updatedData to the data.json file.
  • If there is some error then if block will run and it will give 500 status code otherwise else block will run that gives status 200.
  • The end line of the code is for starting the server on port 8000.

Post Summary

In this post, I set up an Express.js server with a (/hello) endpoint. When a POST request is made to /hello url then the server adds a new entry with a new ID to the data.json file.

Share this