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 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.


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();
//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 }));

Once configured you can use 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.'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.

  "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();
  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.


When user click on log-in button on HTML page we will POST request to Server and get the response.'/login',function(req,res){
  var user_name=req.body.user;
  var password=req.body.password;
  console.log("User name = "+user_name+", password is "+password);

Here is complete Server code.

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

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

  var user_name=req.body.user;
  var password=req.body.password;
  console.log("User name = "+user_name+", password is "+password);
  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.

    <title>Simple login</title>
    <script src="//">  </script>
        var user,pass;
          $.post("http://localhost:3000/login",{user: user,password: pass}, function(data){
                alert("login success");
    <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">

Here is a video of developing app.


Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Related Posts


  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 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 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’,
    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();
    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, bodyString, options)
    .map(response => response.json())

  11. Here is the Express code….

    // Insert a new resume project“/api/resume/newProject”, function(req, res) {
    //for new projects we will calculate the uid
    var uid = “2”; //req.param(‘uid’);
    var name =;
    var year = req.body.year;
    var note = req.body.note;
    var type = req.body.type;
    function(err, result) {
    if(err) {

    1. Can you paste the error trace? If it is “Headers already sent” then try to remove the res.end() from error and success block and put return in error block.

  12. Thanks a lot – very good.
    For those finding this article now and dont want to use jQuery this will do the same (in ‘newer browsers):
    method: “POST”,
    body: { user: “user”, password: “pass” }

  13. Can someone pls tell me how to fetch data from text field inside the radio button (additional component which exposes when we click the radio button)

Leave a Reply to John Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.