Open In App

How to get Post Data in Node ?

Last Updated : 18 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Node is an open-source, cross-platform runtime environment developed on Chrome’s V8 JavaScript engine, designed for executing JavaScript code outside a web browser.

It’s essential to note that Node.js is neither a framework nor a programming language. The HTTP POST method is supported by Node.js, allowing the transmission of data to a server.

In Express, the `app.post()` method is employed to handle incoming POST requests. The fundamental syntax for utilizing the `app.post()` method is outlined below.

The post data is provided to us on the req object inside the callback function of the app.post() method. We can access the data sent as the body using the syntax mentioned below.

const bodyContent = req.body;

Similarly, if we want to access the header content then we can do so using the syntax mentioned below. 

const headerContent = req.headers;

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: After following the steps your project structure will look like.

Example: Below is the basic example to get POST Data using nodejs:

  • HTML Form with Inputs:
    • The index.html file includes a form with two inputs for username and password.
  • POST Request Handling:
    • 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.
  • Server Response and Console Logging:
    • 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.

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'
        );
    });


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>


Steps to run the App:

node app.js

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads