• PHP
  • JSP
  • SQL Tutorial
  • Core Java
  • jQuery
  • JavaScript
  • RubyonRails
  • Spring
  • Struts

  • <

    Express.js POST Request

    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 Example



    index.html
    
    <html>
      <head>
        <title>Basic User Information</title>
      </head>
      <body>
          <form action="http://localhost:8888/process_get" method="POST">
                First Name: <input type="text" name="first_name"> <br>
                Last Name: <input type="text" name="last_name"> <br>
                   Gender: <select name="gender">
                              <option value="Male">Male</option>
                              <option value="Female">Female</option>
                            </select> 
                      <input type="submit" value="submit">        
          </form>
      </body>
    </html>
    


    server.js
    
    //import the express module
    var express = require('express');
    
    //import body-parser
    var bodyParser = require('body-parser');
    
    //store the express in a variable 
    var app = express();
    
    //configure body-parser for express
    app.use(bodyParser.urlencoded({extended:false}));
    app.use(bodyParser.json());
    
    //allow express to access our html (index.html) file
    app.get('/index.html', function(req, res) {
            res.sendFile(__dirname + "/" + "index.html");
        });
    
    //route the GET request to the specified path, "/user". 
    //This sends the user information to the path  
    app.post('/user', function(req, res){
            response = {
                first_name : req.body.first_name,
                last_name : req.body.last_name,
                gender: req.body.gender
                };
            
            //this line is optional and will print the response on the command prompt
            //It's useful so that we know what infomration is being transferred 
            //using the server
            console.log(response);
            
            //convert the response in JSON format
            res.end(JSON.stringify(response));
        });
    
    //This piece of code creates the server  
    //and listens to the request at port 8888
    //we are also generating a message once the 
    //server is created
    var server = app.listen(8888, function(){
            var host = server.address().address;
            var port = server.address().port;
            console.log("Example app listening at http://%s:%s", host, port);
        });
    
    
    
    
















    © copyright 2017-2021 Completedone pvt ltd.