Express JS retrieve post data

Express JS retrieve post data

In this chapter you will learn how to retrieve post data with Express JS.

To retrieve post data we will use the body-parser module.

To install the body-parser module you need to run npm install body-parser --save command on your terminal.

After installing the body-parser module –

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

// parse application/x-www-form-urlencoded

app.get('/', (req, res) => {
    res.send(`<form action="" method="POST">
    <input type="text" name="username" placeholder="Username">
    <input type="submit">
})'/', (req, res) => {
    // console.log(req.body)
    let result = req.body.username;
    res.send(`Username is : ${result}`);

app.listen(3000, () => console.log('Your app listening on port 3000'));

http://localhost:3000/ – with get request

Browser Output
express retrieve post data

http://localhost:3000/ – with post request

Browser Output
Username is : John Doe

Learn Morebody-parser

Posts Navigation