Request & Response
Resources for Request: Link
Resources for Response: Link
Express.js Request and Response objects
- Express.js Request and Response objects are the parameters of the callback function which is used in Express applications.
- The express.js request object (req) represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.
- The response object (res) specifies the HTTP response which is sent by an Express app when it gets an HTTP request.
You can print req and res objects which provide a lot of information related to HTTP request and response including cookies, sessions, URL, etc.
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
- using Multer
- using Express-fileupload
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);