Handle GET and POST Request in Express

GET and POST is two common HTTP Requests used for building REST APIs. Both of these calls are meant for some special purpose.

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

LIVE DEMO DOWNLOAD

Express framework provides router() method to create HTTP endpoints. Let’s checkout how to handle GET and POST request using Express.

If you are new to Node then you should checkout our detailed Node course. Its FREE!

GET request:

Handling GET request in Express is pretty straightforward. You have to create instance of express and router. Here is small snippet to achieve the same.

const express = require("express");
const router = express.Router();
const app = express();

router.get('handle',(request,response) => {
    //code to perform particular action.
    //To access GET variable use req.query() and req.params() methods.
});

// add router in the Express app.
app.use("/", router);

GET requests can be cached and remains in the browser history. This is why the GET method is not recommended to use for sensitive data (passwords, ATM pins, etc). You should GET requests to retrieve data from the server only.

Let’s checkout the POST method.

POST Request:

Express requires an additional middleware module to extract incoming data of a POST request. This middleware is called as ‘body-parser’. We need to install it and configure it with Express instance.

You can install body-parser using the following command.

sudo npm install --save body-parser

You need to import this package in your project and tell Express to use this as middleware. Refer this code for a reference.

const express = require("express");
const bodyParser = require("body-parser");
const router = express.Router();
const app = express();

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

router.post('handle',(request,response) => {
    //code to perform particular action.
    //To access POST variable use req.body()methods.
    console.log(request.body);
});

// add router in the Express app.
app.use("/", router);

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

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 the client to send user name and password to Server.

Let’s create a new Node.js project.

npm init --y

Let’s install the dependencies.

npm i --S express body-parser

Next, let’s create an Express web Server.

const express = require("express");
const bodyParser = require("body-parser");
const router = express.Router();
const app = express();

app.listen(3000,() => {
  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.

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

router.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
const express = require("express");
const bodyParser = require("body-parser");
const router = express.Router();
const app = express();

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

router.get('/',(req, res) => {
  res.sendfile("index.html");
});

router.post('/login',(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,() => {
  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==='yes') {
                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 demonstration of the app.