Friday, April 17, 2020

Request and Response Objects

Express sends us two objects in this callback, which we called req and res, they represent the Request and the Response objects.
  • Request is the HTTP request. It gives us all the request information, including the request parameters, the headers, the body of the request, and more.
  • Response is the HTTP response object that we’ll send to the client.

Request Object in Express:
request.url           : URL of current object
request.method   : GET | POST
request.headers  : Used to read headers sent from browser to server
request.query      : Used to read query string parameters in the form of object [GET                                        request] Ex: {username:”abc”, password:”xyz”}
request.body       : Used to read query string parameters in the form of object [POST                                      request]. Ex: {username:”abc”, password:”xyz”}

Response Object in Express:
response.write()       : Passes string values to browser
response.end()         : Ends of the response
response.headers()  : Send response headers from server to browser
response.status()      : Used to set status code
response.sendFile()  : Used to read content of file and send the same response to browser
response.send()        : Used to read send string/object to browser
response.json()         : Used to read send json data to browser

Lets create an application that will describe Request and Response Objects:

 reqRes.js
const express = require('express');
const app = express();

app.get('/', (reqres=> {
  console.log(req.url);
  console.log(req.method);
  console.log(req.headers);
  console.log(req.query);
  console.log(req.body);

  res.header('content-type''text/html');
  res.status(500);
  res.write('This is a reply from server<br>');
  res.write('This is another reply from server');
  res.end();

  res.send('This is reply from server to browser using send()');
  // But you can send only one response using res.send()

  res.sendFile(__dirname + '/login.html');

  res.json([
    { id: 1name: "pankaj" },
    { id: 2name: "sachin" },
   ]);
});

app.listen(3000, () => {
  console.log('Server is Running on 3000');

});

Output : http://localhost:3000/?x=10&y=20

Request Objects 
Response Objects