Request & Response

Express.js Request and Response objects

Request Object

Syntax

app.get("/", function (req, res) {});

Response Object

The response object specifies the HTTP response when an Express app gets an HTTP request.
The response is sent back to the client browser and allows you to set new cookies value that will write to the client browser.

In thie Topic 1, we have seen a basic application which serves HTTP request for the homepage.
Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

πŸ“ Now, let’s code to a program to handle more types of HTTP requests. You can see code in Code Folder. Here’s the Link

You can run it by doing -

npm install

node server.js

You will see following output -

Example app listening at "http://localhost:8081/"

Now you can try different requests at http://localhost:8081 to see the output generated by server.js. For example. http://localhost:8081/list_user, http://localhost:8081/del_user, http://localhost:8081/abcd, http://localhost:8081/ab123cd, etc.

File Uploader

πŸ“ Let’s try to make a file uploader form. You can see code in Code Folder. Here’s the link

There are 2 ways of file uploading

You can run it by doing -

npm install

node server1.js (for Multer One)
or
node server2.js (for Express-fileupload One)

You will see following output -

Listening at "http://localhost:8081/"

Cookies Management

You can send cookies to a Node.js server which can handle the same using the following middleware option. Following is a simple example to print all the cookies sent by the client.

var express = require("express");
var cookieParser = require("cookie-parser");

var app = express();
app.use(cookieParser());

app.get("/", function (req, res) {
  console.log("Cookies: ", req.cookies);
});

app.listen(8081);