Example method POST in express

1. create file post.html

 

<html>

   <body>

      <form action = "http://localhost:8080/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>

 

2. create express_method_post.js

 

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 + "/" + "post.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("Server listening at http://%s:%s", host, port);

 

});

Run server and go browser http://localhost:8080/index.html

Input first name, last name then submit: