Express.js POST Method

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

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.use(express.static('public'));  
app.get('/index.html', function (req, res) {  
   res.sendFile( __dirname + "/" + "index.html" );  
})  
app.post('/process_post', urlencodedParser, function (req, res) {  
   // Prepare output in JSON format  
   response = {  
       first_name:req.body.first_name,  
       last_name:req.body.last_name  
   };  
   console.log(response);  
   res.end(JSON.stringify(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.

express-post-method

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).

express-post-method-json

Subscribe Now