Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to get Post Data in Node.js ?

  • Last Updated : 20 Nov, 2021

Node.js is an open-source and cross-platform runtime environment built on Chrome’s V8 JavaScript engine for executing JavaScript code outside of a browser. You need to recollect that NodeJS isn’t a framework, and it’s not a programming language. In this article, we will discuss how to make post request using node.js

POST is a request method supported by HTTP that sends data to the server. In express, we can use the app.post() method to accept a POST request. The basic syntax to use the app.post() method is mentioned 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;

Project Setup:



Step 1: Install Node.js if Node.js is not installed in your machine.

Step 2: Create a folder for your project and created two files named app.js and index.html inside of it.

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

npm init -y

Step 4: 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.

Filename: app.js

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

Filename: index.html

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>

In the above example, we have created an express server that renders the index.html file. This index.html contains a form that has two inputs as username and password. When we press the submit button it sends a POST request to the home route with the body containing the username and password and the header containing the authorization token. We handle this post request inside our app.post() method and send these details i.e., the username, password, and authorization token as a response. We later print these details to the console.

Run app.js file using below command:

node app.js

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!