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 Post Data in MongoDB Using NodeJS?
Next article icon

How to Get POST Data in Node ?

Last Updated : 08 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Handling POST data is a fundamental aspect of developing web applications and APIs using Node.js. POST requests are used when a client needs to send data to the server, such as submitting form data, uploading files, or sending JSON payloads. This article will cover various methods to retrieve and handle POST data in Node.js, enhancing your server-side capabilities.

Introduction to POST Requests

POST requests are a type of HTTP request used to send data to the server to create or update resources. Unlike GET requests, which append data to the URL, POST requests include data in the request body, making them suitable for sending large amounts of data or sensitive information.

The following approaches can be used to get POST Data in Node:

Table of Content

  • Using the HTTP Module
  • Using the querystring Module
  • Using Express

Getting POST data is a common task when building forms and APIs.

Steps to Create the Application

Step 1: Now, initialize a new Node.js project with default configurations using the following command on the command line.

npm init -y

Step 2: Now install Express inside your project using the following command on the command line.

npm install express

Project Structure:

Using the HTTP Module

You can handle POST data by creating an HTTP server using Node.js's built-in http module. Here's a basic example of how to parse POST data.

Approach:

In this approach Node.js HTTP server listens on port 3000, handles POST requests by collecting and logging incoming data, then responds with a confirmation message. Non-POST requests receive a prompt to send POST data.

const http = require('http');

const server = http.createServer((req, res) => {
if (req.method === 'POST') {
let data = '';
req.on('data', chunk => {
data += chunk.toString();
});
req.on('end', () => {
console.log('POST data:', data);
res.end('Data received');
});
} else {
res.end('Send a POST request to this endpoint');
}
});

server.listen(3000, () => {
console.log('Server running on port 3000');
});

Using the querystring Module

If the POST data is in URL-encoded format, you can use the querystring module to parse it.

Approach:

Use Node.js's http module to handle POST requests, accumulating incoming data, parsing it with querystring, and then logging and responding with a confirmation message.

const http = require('http');
const querystring = require('querystring');

const server = http.createServer((req, res) => {
if (req.method === 'POST') {
let data = '';
req.on('data', chunk => {
data += chunk.toString();
});
req.on('end', () => {
const postData = querystring.parse(data);
console.log('POST data:', postData);
res.end('Data received');
});
} else {
res.end('Send a POST request to this endpoint');
}
});

server.listen(3000, () => {
console.log('Server running on port 3000');
});

Using Express

Express.js simplifies the process of handling HTTP requests, including POST requests. Let's dive into a practical example of handling POST data with Express.js:

Approach:

  • The index.html file includes a form with two inputs for username and password.
  • When the form is submitted, a POST request is sent to the home route ("/") of the server.
  • The request body contains the username and password, and the header includes an authorization token.
  • The server handles the POST request using the app.post() method.
  • The server responds by sending back the username, password, and authorization token.
  • These details are printed to the console for further examination.

Example: Implementation to show how to get POST data in nodejs.

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8" />     <title>POST DEMO</title> </head>  <body>     <form>         <div>             <label>Username</label>             <input type="text" id="user" />         </div>         <div>             <label>Password</label>             <input type="password"                     id="pass" />         </div>         <button type="submit">             Submit           </button>     </form>      <script>         document.querySelector('button')             .addEventListener('click', (e) => {                 e.preventDefault();                 const username = document                     .querySelector('#user').value;                  const password = document                     .querySelector('#pass').value;                                      fetch('/', {                     method: 'POST',                     headers: {                         Authorization: 'Bearer abcdxyz',                         'Content-Type': 'application/json',                     },                     body: JSON.stringify({                         username,                         password,                     }),                 })                     .then((res) => {                         return res.json();                     })                     .then((data) => console.log(data));             });     </script> </body>  </html> 
JavaScript
// Importing express module const express = require('express'); const app = express();  app.use(express.json());  app.get('/',     (req, res) => {         res.sendFile(__dirname + '/index.html');     });  app.post('/',     (req, res) => {         const { username, password } = req.body;         const { authorization } = req.headers;         res.send(             {                 username,                 password,                 authorization,             });     });  app.listen(3000,     () => {         console.log(             'Our express server is up on port 3000'         );     }); 

Steps to run the Application

node app.js

Output: Open the browser and go to http://localhost:3000 and you will see the following output.

Conclusion

Handling POST data in Node.js is a crucial aspect of building server-side applications. Whether you're using built-in modules, middleware, or third-party libraries, understanding how to retrieve and process POST data is essential for building robust and scalable web applications. Choose the method that best fits your project's requirements and development preferences to efficiently handle POST requests in Node.js.


Next Article
How to Post Data in MongoDB Using NodeJS?
author
shivamsingh00141
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Express.js
  • NodeJS-Questions

Similar Reads

  • How to Post Data in MongoDB Using NodeJS?
    In this tutorial, we will go through the process of creating a simple Node.js application that allows us to post data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. And also we use the Ejs for our front end to render the simple
    5 min read
  • How to get form data using POST method in PHP ?
    PHP provides a way to read raw POST data of an HTML Form using php:// which is used for accessing PHP’s input and output streams. In this article, we will use the mentioned way in three different ways. We will use php://input, which is a read-only PHP stream. We will create a basic HTML form page wh
    2 min read
  • How to create a new request in Postman?
    Postman is a development tool that is used for testing web APIs i.e. Application Programming Interfaces. It allows you to test the functionality of any application's APIs. Almost every developer uses Postman for testing purposes. We can create any type of HTTP request in it such as GET, POST, PUT, D
    2 min read
  • How to Upload File and JSON Data in Postman?
    Postman is a very famous API development tool used to test APIs. Postman simplifies the process of the API lifecycle to create and test better APIs. Now, while we are working with APIs sometimes we need to send JSON as data or upload a file through API. There may be a scenario where we have to do bo
    4 min read
  • How to Get Data from MongoDB using Node.js?
    One can create a simple Node.js application that allows us to get data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. Also, we use the EJS for our front end to render the simple HTML form and a table to show the data. Prerequisi
    6 min read
  • How to Handle a Post Request in Next.js?
    NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. In this article, we will learn about How to handle a post request in NextJS. A
    2 min read
  • Python Falcon - get POST data
    In this discussion, we will delve into retrieving Python Falcon - get POST data. Falcon is a lightweight and speedy web framework explicitly crafted for constructing RESTful APIs. Effective handling of POST data is essential in API development, enabling the creation, updating, or manipulation of res
    4 min read
  • How to Post JSON Data to Server ?
    In modern web development, sending JSON data to a server is a common task, especially when working with RESTful APIs. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write for humans and easy to parse and generate for machines. This article will gu
    4 min read
  • How to Connect Node to a MongoDB Database ?
    Connecting Node.js to MongoDB is a common task for backend developers working with NoSQL databases. MongoDB is a powerful, flexible, and scalable database that stores data in a JSON-like format. In this step-by-step guide, we'll walk through the entire process from setting up your development enviro
    6 min read
  • How HTTP POST requests work in Node ?
    The HTTP POST method is used to send data from the client to the server. Unlike GET, which appends data in the URL, POST sends data in the request body, which makes it ideal for form submissions, file uploads, and secure data transfers. In Node.js, handling POST requests is commonly done using the E
    2 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