Express.js POST Method

Lets modify our index.html with post method as below.
<form action="" method="POST">  
First Name: <input type="text" name="first_name">  <br> 
Last Name: <input type="text" name="last_name">  
<input type="submit" value="Submit">  

Lets update our server.js which contains the route by adding a route for POST method.
var express = require('express');  
var app = express();  
var bodyParser = require('body-parser');  
// Create application/x-www-form-urlencoded parser  
var urlencodedParser = bodyParser.urlencoded({ extended: false })  
app.get('/index.html', function (req, res) {  
   res.sendFile( __dirname + "/" + "index.html" );  
})'/process_post', urlencodedParser, function (req, res) {  
   // Prepare output in JSON format  
   response = {  
var server = app.listen(8080, function () {  
  var host = server.address().address  
  var port = server.address().port  
  console.log("Example app listening at http://%s:%s", host, port)  

Here we have added a body-parser module to our application. When using a post method it comes in handy and with lesser code. We used req.query to fetch the values from a query string which is part of GET Method. Here in POST, we use req.body to fetch the values.

We can run the code using node server.js , the app will be running and listening to port 8080.

Open the url localhost:8080/index.html in the browser and fill in the input fields and then submit to check POST method functionality.

Below screenshot shows the output of above code.


Below screen shot shows the output on the browser, we can see that the POST method is used. (there is no Query string in the url after form submit).


Subscribe Now