menu

Handle GET and POST Request in Express 4

POST and GET are two common HTTP Request used for building REST API’s. Both of these calls are meant for some special purpose.

As per the documentation GET request are meant to fetch data from specified resource and POST are meant to submit data to a specified resource.

LIVE DEMO DOWNLOAD

Express allows you to handle GET and POST request using the instance of express. Due to the depreciation of connect middle-ware handling POST request however seems confusing to many people.

If you are new to Node and Express then you won’t regret taking our Node course. Its FREE!

GET request:

Handling GET request in Express seems so easy. You have to create instance of express and call get method. Here is small snippet to demonstrate that.

var express        =        require("express");
var app            =        express();
app.get('handle',function(request,response){
//code to perform particular action.
//To access GET variable use.
//request.var1, request.var2 etc
});

GET request can be cached and remains in browser history. This is why GET is not supposed to use for sensitive data (passwords, ATM pins, etc). GET are suppose to use to retrieve data only.

POST Request:

Express version 4 and above require extra middle-ware layer to handle a POST request. This middle-ware is called as ‘bodyParser’. This used to be an internal part of Express framework but now you have to install it separately.

You can install bodyParser by two way. Either by mentioning it in package.json or simply executing following command to download and put it in package file.

sudo npm install --save body-parser

You have to import this package in your project and tell Express to use this as middle-ware. To do so here is a code.

var express        =        require("express");
var bodyParser     =        require("body-parser");
var app            =        express();
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

Once configured you can use app.post express router to handle POST request. To access the POST query variable you can use request_variable.body.post_variable. 
Here is a snippet to demonstrate the code.

app.post('handle',function(request,response){
var query1=request.body.var1;
var query2=request.body.var2;
});

In this way you can handle the GET and POST request in Express 4.

Demo App : Login System

To demonstrate this i am going to code one simple log-in System which will use GET request to serve HTML page to client and POST request from client to send user name and password to Server. So let’s create our package.json file.

package.json
{
  "name": "get-post-demo",
  "version": "0.0.1",
  "dependencies": {
    "body-parser": "^1.8.1",
    "express": "^4.9.0"
  }
}

Install dependencies using

npm install

Next we will create Express web Server.

var express        =        require("express");
var bodyParser     =        require("body-parser");
var app            =        express();
app.listen(3000,function(){
  console.log("Started on PORT 3000");
})

Run Server using

node server.js

We will use Express Router to handle routes of app. So when user request the app from web browser, we will serve the HTML file.

app.get('/',function(req,res){
  res.sendfile("index.html");
});

When user click on log-in button on HTML page we will POST request to Server and get the response.

app.post('/login',function(req,res){
  var user_name=req.body.user;
  var password=req.body.password;
  console.log("User name = "+user_name+", password is "+password);
  res.end("yes");
});

Here is complete Server code.

server.js
var express        =         require("express");
var bodyParser     =         require("body-parser");
var app            =         express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/',function(req,res){
  res.sendfile("index.html");
});
app.post('/login',function(req,res){
  var user_name=req.body.user;
  var password=req.body.password;
  console.log("User name = "+user_name+", password is "+password);
  res.end("yes");
});
app.listen(3000,function(){
  console.log("Started on PORT 3000");
})

On front-end we will create simple HTML file and call the POST request using Ajax. Here is a code of HTML page.

index.html
<html>
  <head>
    <title>Simple login</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">  </script>
    <script>
      $(document).ready(function(){
        var user,pass;
        $("#submit").click(function(){
          user=$("#user").val();
          pass=$("#password").val();
          $.post("http://localhost:3000/login",{user: user,password: pass}, function(data){
            if(data==='done')
              {
                alert("login success");
              }
          });
        });
      });
    </script>
  </head>
  <body>
    <h1>Hello people !</h1>
    <input type="TEXT" id="user" size="40"><br>
    <input type="password" id="password" size="40"><br>
    <input type="button" id="submit" value="Submit">
  </body>
</html>

Here is a video of developing app.