NodeJS : Accessing POST method data with Sample Code

In NodeJS we can able to access the POST method request data using the “body-parser” module. This module parse the request by encoding the URL by calling the function. This urlencoded function accepts JSON object as input.

Syntax:

var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: true });
 
app.post('/POST_REQ/URL', urlencodedParser, function (req, res){
  FIELD_NAME = req.body.POST_FIELD_NAME;
});

Example:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: true });
 
// Running Server Details.
var server = app.listen(8082, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("Example app listening at %s:%s Port", host, port)
});
 
 
app.get('/form', function (req, res) {
  var html='';
  html +="<body>";
  html += "<form action='/thank'  method='post' name='form1'>";
  html += "Name:</p><input type= 'text' name='name'>";
  html += "</form>";
  html += "</body>";
  res.send(html);
});
 
app.post('/thank', urlencodedParser, function (req, res){
  var name = req.body.name;
  res.send(name);
 });
Category: