HI WELCOME TO SIRIS

Express.js POST Request

Leave a Comment
GET and POST both are two common HTTP requests used for building REST API's. POST requests are used to send large amount of data.
Express.js facilitates you to handle GET and POST requests using the instance of express.

Express.js POST Method

Post method facilitates you to send large amount of data because data is send in the body. Post method is secure because data is not visible in URL bar but it is not used as popularly as GET method. On the other hand GET method is more efficient and used more than POST.
Let's take an example to demonstrate POST method.
Example1:
Fetch data in JSON format
File: Index.html
  1. <html>  
  2. <body>  
  3. <form action="http://127.0.0.1:8000/process_post" method="POST">  
  4. First Name: <input type="text" name="first_name">  <br>  
  5. Last Name: <input type="text" name="last_name">  
  6. <input type="submit" value="Submit">  
  7. </form>  
  8. </body>  
  9. </html>  
File: post_example1.js
  1. var express = require('express');  
  2. var app = express();  
  3. var bodyParser = require('body-parser');  
  4. // Create application/x-www-form-urlencoded parser  
  5. var urlencodedParser = bodyParser.urlencoded({ extended: false })  
  6. app.use(express.static('public'));  
  7. app.get('/index.html', function (req, res) {  
  8.    res.sendFile( __dirname + "/" + "index.html" );  
  9. })  
  10. app.post('/process_post', urlencodedParser, function (req, res) {  
  11.    // Prepare output in JSON format  
  12.    response = {  
  13.        first_name:req.body.first_name,  
  14.        last_name:req.body.last_name  
  15.    };  
  16.    console.log(response);  
  17.    res.end(JSON.stringify(response));  
  18. })  
  19. var server = app.listen(8000, function () {  
  20.   var host = server.address().address  
  21.   var port = server.address().port  
  22.   console.log("Example app listening at http://%s:%s", host, port)  
  23. })  
Post Request
Open the page index.html and fill the entries:
Post Request
Now, you get the data in JSON format.
Post Request Post Request

Note: In the above picture, you can see that entries are not visible in the URL bar unlike GET method.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.