Saturday, April 18, 2020

Handling GET and POST Request

GET and POST 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.

GET request:
Handling GET request in Express seems so easy. You have to create instance of express and call get method.

Login.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h2>Login Form</h2>
    <form action="/login.html" method="GET">
      Username <input type="text" name="uname" /><br /><br />
      Password <input type="password" name="pwd" /><br /><br />
      <input type="submit" value="LOGIN" />
    </form>
  </body>
</html>

GetReq.js
const express = require('express');
const app = express();
app.listen(3000, () => {
  console.log('Server is Running on 3000');
});

app.get('/', (reqres=> {
  res.sendFile(__dirname + '/login.html');
});
app.get('/login.html', (reqres=> {
  if (req.query.uname == 'admin' && req.query.pwd == '123') {
    res.send('Successful Login');
  } else {
    res.send('Invalid Login');
  }
});

// Fallback function
app.use(function (reqres) {
  res.write('No page here');
  res.end();
});

Output:

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

Login.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h2>Login Form</h2>
    <form action="/login.html" method="POST">
      Username <input type="text" name="uname" /><br /><br />
      Password <input type="password" name="pwd" /><br /><br />
      <input type="submit" value="LOGIN" />
    </form>
  </body>
</html>

PostReq.js
const express = require('express');
const app = express();
app.listen(3000, () => {
  console.log('Server is Running on 3000');
});

//body-parser
const bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());

app.get('/', (reqres=> {
  res.sendFile(__dirname + '/login.html');
});
app.post('/login.html', (reqres=> {
  console.log(req.body);
if (req.body.uname == 'admin' && req.body.pwd == '123') {
  // to use request.body, you need to import body-parser package
    res.send('Successful Login');
  } else {
    res.send('Invalid Login');
  }
});

// Fallback function
app.use(function (reqres) {
  res.write('No page here');
  res.end();
});

Output: