GET and POST Request Express

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 call’s 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.

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 suppose 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 requires extra middle-ware layer to handle POST request. This middle-ware is called as ‘bodyParser’. This used to be 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.

Shahid (UnixRoot) Shaikh

Hey there, This is Shahid, an Engineer and Blogger from Bombay. I am also an Author and i wrote a programming book on Sails.js, MVC framework for Node.js.

Related Posts

47 Comments

  1. I got one question for you, do we need to hide our endpoint here to prevent anyone can send request to your server(/login) without going thru your client page? If so, what strategy should we use?

    1. We can prevent IP to send request to our Server. If IP is from other than allowed network then it won’t accept the request. Please look over access-control and allow-origin headers parameters of HTTP.

  2. Once again a resourceful post. Thanks!

    However, I have a doubt. Will that alert get fired? Because, you are sending ‘yes’ as response and checking for ‘done’ in the html.

    When I tried with specific ‘success’ function and compare with ‘yes’, it worked.

    Please correct me if I am wrong.

  3. I cannot get this example to work from another computer.
    If I run the server.js on machine 1 (which as an IP of say 10.45.32.102) and go to localhost:3000 everything works as expect.

    However when I try to access this page from another computer (on the same network) by doing 10.45.32.102:3000 the Simple Login page shows up but when I hit the submit button It will not POST to the server. I don’t think the jquery is working in this particular instance could you help? The example is nice. But I want people from the network to be able to access the page.

  4. i open a connection using java httpurl connection and write data in output stream but
    am not able to read input stream using node express. iam able to read using http module not in express
    how to read request input stream using express4

  5. If i had an array of items on my server that i wanted to search from the front end and have it return valid results how would i use post and get (or either) to do this? If search took a long time how would i tackle this?

    1. You need to use POST cause you have to pass some data to SERVER. Pass the data, use indexOf() to search in array and if found return the value.

      How to tackle if its slow ? If you get so much large data then you need to implement some search Algorithm like Binary search etc to improve the speed also update the SERVER configuration.

  6. Hi author, I want the same thing but the slight change in that, In file I have only one POST API which server the response. The requesting is coming from another server.
    Input is Json like :
    {
    name: ‘Veeresh’,
    age:100
    }
    Output:
    Just print input in browser.

  7. Hello I am so delighted I found your site, I really found you by
    accident, while I was searching on Yahoo for something else, Anyhow
    I am here now and would just like to say thanks a lot
    for a fantastic post and a all round enjoyable blog (I also love the theme/design), I don’t have time to go through it all at the moment but I have saved it and also added
    in your RSS feeds, so when I have time I will be back to read more, Please do keep
    up the superb work.

  8. Please look at this and advice me asap please I need it 4 my project .
    Here’s how my login system works. I am using was as engine with /views as folder for views. I will skip lots of details
    var router =express.Router();
    …..
    router.get(‘/’,fxn(req,res){
    res.render(‘index’); //working
    }
    router. post(‘/login’, function(req,res){
    console.log(‘test login’); //working
    res.render(‘users/index’,{ some json data here }); // not working
    }

    Everything is well set so no working except the part for rendering a view after a post request. Maybe an example will help using express.Router()

    1. Hi Brian,
      Its seems to be a routing issue. Please verify the route you provided for the post method is correct.

  9. Great simple example, thanks! Saved my day, wasn’t able to get those req params, thought that “body” usage dedicated to the html elements only…

  10. can you see any reason why this Angular2 observable call would cause the same Express POST to crash?

    public AddProject (body : string): Observable {
    let bodyString = JSON.stringify(body); // Stringify payload
    let headers
    = new Headers({ ‘Content-Type’: ‘application/json’,
    ‘Accept’: ‘q=0.8;application/json;q=0.9’ }); // … Set content type to JSON
    let options = new RequestOptions({ headers: this.headers });
    return this.http.post(this.actionUrlnewProject, bodyString, options)
    .map(response => response.json())
    .catch(this.handleError);
    }

  11. Here is the Express code….

    // Insert a new resume project
    app.post(“/api/resume/newProject”, function(req, res) {
    //for new projects we will calculate the uid
    var uid = “2”; //req.param(‘uid’);
    var name = req.body.name;
    console.log(“req.body.name:”, req.body.name);
    var year = req.body.year;
    var note = req.body.note;
    var type = req.body.type;
    db.collection(“wr_project”).insert(
    {
    “uid”:uid,
    “name”:name,
    “year”:year,
    “note”:note,
    “type”:type
    },
    function(err, result) {
    if(err) {
    res.json(err);
    res.end(“yes”);
    };
    res.json(result);
    res.end(“yes”);
    });
    });

Leave a Reply

Your email address will not be published. Required fields are marked *