Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to insert request body into a MySQL database using Express js
Next article icon

How to resolve req.body is empty in posts error in Express?

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Express the req.body is empty error poses a critical challenge in web development, particularly in the context of processing POST requests on the server side. This issue arises when the server encounters difficulties parsing the request body, resulting in an empty or undefined req.body object. Developers looking for dependable data handling mechanisms may become frustrated by this obstacle, which can impede the smooth flow of data between clients and servers.

Causes of req.body is empty Error:

  • Missing middleware configuration for parsing the body during post request.
  • An incorrect header is used when calling a post request from the client.

How to Resolve req.body is empty error:

Approach 1: Middleware Configuration

Ensure you have implemented the necessary middlewares for parsing the data for post requirements . In express, express.json and express.urlencoded are built-in functions for parsing post request.

Approach 2: Correct Header for Calling Post request from client side.

When calling the APIs using fetch make sure the Content-Header has application/json or application/x-www-form-urlencoded in the payload. We will now see how to implement with the example below

Steps to create Express Application

Step 1: Create a folder using the command and initialize the node project using the command

mkdir foldername
cd foldername
npm init -y

Step 2: Create the necessary files

touch index.js

Step 3: Installing the necessary modules

npm i express cors

Example 1: We will create a simple express server that will take data using post request and we will show how to use the express.json() function and express.urlencoded() function and will use postman to call the api

JavaScript
const express = require('express'); const app = express(); const port = 3000; app.use(express.urlencoded({ extended: true })); // This is required to handle urlencoded data app.use(express.json());  // This to handle json data coming from requests mainly post  app.post('/api/data', (req, res) => {     // Handle the POST request here     const data = req.body;     // Send a response back to the client     res.status(200).json({ data: data, message: 'Data received successfully' }); });  app.listen(port, () => {     console.log(`Server is running on port ${port}`); }); 

Steps to run the project

Step 1: Enter the following command to run the project

node index.js

Step 2: Open postman and open a new request and call the api using post and send the data in json and urlencoded format

Output:

express1

Example 2: We will create client (html page) to call our api data using fetch function and will show how to use content/application-json to call the post request

JavaScript
const express = require('express'); const app = express(); const port = 3000; const cors = require("cors"); // This is required to handle urlencoded data app.use(express.urlencoded({ extended: true }));  app.use(express.json());  // This to handle json data coming from requests mainly post app.use(cors("*")) // This Cross Origin Handling app.post('/api/data', (req, res) => {     // Handle the POST request here     const data = req.body;     // Send a response back to the client     res.status(200).json(       { data: data, message: 'Data received successfully' }); }); app.post('/api/content', (req, res) => {     // Handle the POST request here     const {name,email,age} = req.body;     data = {name:name,email:email,age:age};     // Send a response back to the client     res.status(200).json(       { data: data, message: 'Data received successfully' }); }); app.listen(port, () => {     console.log(`Server is running on port ${port}`); }); 
HTML
<!DOCTYPE html> <html> <head>     <title>API Request</title>     <style>         body {             font-family: Arial, sans-serif;             background-color: #f2f2f2;         }          h1 {             text-align: center;             color: #333;         }          div {             max-width: 400px;             margin: 0 auto;             padding: 20px;             background-color: #fff;             border-radius: 5px;             box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);         }          label {             display: block;             margin-bottom: 10px;             color: #333;         }          input[type="text"],         input[type="email"],         input[type="number"] {             width: 100%;             padding: 10px;             border: 1px solid #ccc;             border-radius: 4px;             box-sizing: border-box;             margin-bottom: 20px;         }          button {             background-color: #4CAF50;             color: white;             padding: 10px 20px;             border: none;             border-radius: 4px;             cursor: pointer;         }          #result {             margin-top: 20px;             padding: 10px;             background-color: #f9f9f9;             border: 1px solid #ccc;             border-radius: 4px;         }     </style> </head> <body>     <h1>API Request</h1>     <div id="myForm">         <label for="name">Name:</label>         <input type="text" id="name" name="name" required><br><br>         <label for="email">Email:</label>         <input type="email" id="email" name="email" required><br><br>         <label for="age">Age:</label>         <input type="number" id="age" name="age" required><br><br>         <button onclick="getData()">Submit</button>     </div>      <div id="result"></div>      <script>         function getData() {             console.log("getData() called");             const name = document.getElementById("name").value;             const email = document.getElementById("email").value;             const age = document.getElementById("age").value;             const data = { name, email, age };              fetch("http://localhost:3000/api/content", {                 method: "POST",                 headers: {                     "Content-Type": "application/json"                 },                 body: JSON.stringify(data)             })             .then(response => response.json())             .then(result => {                 console.log(result);                 document.getElementById("result").innerHTML                   = JSON.stringify(result);                 // Display the API response in the "result" div             })             .catch(error => {                 console.error(error);                 // Handle any errors here             });         };     </script> </body> </html> 

Steps to run the project

Step 1: Enter the following command to run the project

node index.js

Step 2: Open html page in the browser and enter the data and click on button then it will display the output

Output:

express2


Next Article
How to insert request body into a MySQL database using Express js
author
ameyabavkar
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Geeks Premier League
  • Express.js
  • Geeks Premier League 2023

Similar Reads

  • How to Redirect 404 errors to a page in Express.js ?
    Express Js is a web application framework based on Node.js web server functionality that helps us to create web servers with lesser complexity and in a well-organized manner. Express provides routing services that help us in creating application endpoints that respond based on the HTTP request metho
    3 min read
  • How To Deal With CORS Error in Express/NodeJS Project?
    Cross-Origin Resource Sharing (CORS) errors occur in ExpressJS applications when a web page attempts to make requests to a domain different from the one that served it, and the server hasn't been configured to allow such requests. CORS errors are common in NodeJS projects when working with APIs. Com
    5 min read
  • How to access Raw Body of a Post Request in Express.js ?
    Raw Body of a POST request refers to unprocessed or uninterpreted data sent in the request before Express or any middleware processes or understands it. It's like raw ingredients before the cooking begins. In this article we will see various approaches to access raw body of a post request in Express
    3 min read
  • How to insert request body into a MySQL database using Express js
    If you trying to make an API with MySQL and Express JS to insert some data into the database, your search comes to an end. In this article, you are going to explore - how you can insert the request data into MySQL database with a simple Express JS app. Table of Content What is Express JS?What is MyS
    3 min read
  • How to Fix ChatGPT "Error in Body Stream"
    ChatGPT has smoothly become an important part of pretty much everyone’s life. The revolutionary AI chatbot has become a go-to tool that assists millions of people in generating blogs, emails, codes, captions, and almost every kind of written content. However, there are times when the chatbot display
    7 min read
  • How to resolve Postman unable to send request body to express application error ?
    Encountering difficulties when attempting to send a request body from Postman to your Express application can be a frustrating experience. This issue may manifest in various ways, such as empty request bodies or unexpected behavior on the server side. In this troubleshooting guide, we will explore d
    4 min read
  • How to add a 404 Error Page in the Express ?
    Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client's different incoming requests. In this article, we will discuss how to add a 404 error page i.e not found using the express server. 404 is the
    1 min read
  • How to receive post parameter in Express.js ?
    Express is a small framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middleware and routing; it adds helpful utilities to Node.js’s HTTP objects; it facilitates the
    3 min read
  • How to Exit after res.send() in Express JS
    In this article, we are going to learn how we can exit after the res.send() function in Express JS. In Express the res.send() method is mainly used to send a response to the client with the specified content. This function automatically sets the Content-Type Header which is based on the data provide
    3 min read
  • How to Install Express in a Node Project?
    ExpressJS is a popular, lightweight web framework for NodeJS that simplifies the process of building web applications and APIs. It provides a robust set of features for creating server-side applications, including routing, middleware support, and easy integration with databases and other services. B
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences