Saturday, June 6, 2020

ExpressJS POST method

ExpressJS POST method


GET and POST are the two most common HTTP methods, used to transfer the HTTP data from the client to the server. The POST method encapsulates request parameters in the message body. This makes it secure to transfer the data from the client to the server.

app.post()


The app.post() routes(read ExpressJs routing) HTTP POST requests to the given path with the provided callback functions.

The path parameter represents the path for which the middleware function is called and it can be any of the following,

  • A string representing a path
  • A path pattern
  • A regex pattern to match paths
  • An array containing combinations of any of these


The Callback functions can be any of the following,

  • A middleware function
  • A series of middleware functions (comma separated)
  • An array of middleware functions
  • A combination containing all of the above

There can be more than one callback functions that behave just like middleware, besides these callback functions can call next('route') to bypass the remaining route callback(s). We can use this technique to impose pre-defined conditions on a route, and then pass the control to the following routes if there is no reason to continue with the current route.

The router and app can be used as any other middleware function because tey implements a middleware interface.


app.post() Example


First write, index.html as follows,

<html>  
<body>  
<form action="http://localhost:3000/post_demo" method="POST">  
<input type="text" name="fname" placeholder="First name">  <br>  
<input type="text" name="lname" placeholder="Last name"> <br> 
<input type="submit" value="Submit">  
</form>  
</body>  
</html>  
Write post_demo as follows,

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('/post_demo', urlencodedParser, function (req, res) {  
   // Prepare output in JSON format  
   fullname = {  
       fname:req.body.fname,  
       lname:req.body.lname  
   };  
   console.log(fullname);  
   res.end(JSON.stringify(fullname));  
})  
var server = app.listen(3000, function () {  
  var host = server.address().address  
  var port = server.address().port  
  console.log("Example app listening at http://%s:%s", host, port)  
});  
run command node post_demo, to execute the code,

The results will be displayed, as