Most Popular Tutorials
Most Popular Tutorials :-

Simply Easy Learning at Your Fingertips. Click Tutorials Menu to view More Tutorial List





How to get Form Post Data in Node.js ?

In node.Js application, You can use the app.post() method to accept a POST request. req object is used to Get the post data inside the callback function of the app.post() method.

File Name :

const bodyContent = req.body;
// To access the header content
const headerContent = req.headers;

Steps : create Node Project

File Name :

  • Step 1:- First install the Node.Js in your system.
  • Step 2:- Create a project Directory. eg. mynode_project
  • Step 3:- C:\mynode_project>
  • Step 4:- Now install express Js inside your project
  • Step 5:- c:\mynode_project> npm install express
  • Step 6 :- create file myapp.js in your project directory.
  • Step 7 :- create file index.html in your project directory.
  • Step 8 :- run your project. C:\mynode_project> node myapp.js

  • Myapp.js

    File Name : myapp.js

    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);
    // app.listen(8080);

    View Page index.html

    File Name : index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>How to get Post data in node.Js</title>
    </head>
    <body>
    <form>
    <div>
    <label>Username</label>
    <input type="text" id="user" name="user"/>
    </div>
    <div>
    <label>Password</label>
    <input type="password" id="pass" name="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: 'mahi',
    'Content-Type': 'application/json',
    },
    body: JSON.stringify({
    username,
    password,
    }),
    })
    .then((res) => {
    return res.json();
    })
    .then((data) => console.log(data));
    });
    </script>
    </body>
    </html>

    Run :-

    File Name :

    c:\mynode_project> node myapp.js

    Test On browser

    File Name :

    in URL :- http://localhost:3000





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here