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.use(bodyParser.urlencoded({extended:false}));

app.get('/', (req, res) => {
    res.send(`<form action="" method="POST">
    <input type="text" name="username" placeholder="Username">
    <input type="submit">
    </form>`);
})

app.post('/', (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'));

Now open this URL http://localhost:3000/  on your browser with the get request

Browser Output
browser output

When you Submit the form (http://localhost:3000/ – with post request) –

Browser Output
Username is : John Doe

Learn More – body-parser


Next is – Template Engines

Previous is – Express JS router

Leave a Reply

Your email address will not be published. Required fields are marked *