Steps to use req and res objects in Express

Step 1: In the first step, we will create the new folder as an http-objects by using the below command in the VScode terminal.

mkdir http-objects
cd http-objects

Step 2: After creating the folder, initialize the NPM using the below command. Using this the package.json file will be created.

npm init -y

Step 3: Now, we will install the express dependency for our project using the below command.

npm i express

Step 4: Now create the below Project Structure of our project which includes the file as app.js.

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"express": "^4.18.2"
}

Example: Write the following code in app.js file

Javascript




const express = require("express");
const app = express();
const port = 3000;
// defining a simple middleware to log requests
app.use((req, res, next) => {
    console.log(`Incoming Request: ${req.method} ${req.url}`);
    next(); // calling the next middleware or route handler
});
app.get("/favicon.ico", (req, res) => {
    res.status(204).end(); // No content for favicon.ico
});
// route handling using req and res objects
app.get("/greet/:name", (req, res) => {
    // accessing URL parameters using req.params
    const geekName = req.params.name;
    // sending a customized HTML response
    const htmlResponse = `
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width,
        initial-scale=1.0">
      <title>Greeting Page</title>
    </head>
    <body>
      <h1>Hello, ${geekName}!</h1>
    </body>
    </html>
  `;
    // logging the response in the terminal
    console.log(`Outgoing Response: ${res.statusCode} ${res.statusMessage}`);
    // sending the HTML response
    res.send(htmlResponse);
});
// start the server
app.listen(port, () => {
    console.log(`Server is running at http://localhost:${port}`);
});


Start the server by using the below command:

node app.js

Output:



Explain the use of req and res objects in Express JS

Express JS is used to build RESTful APIs with Node.js. We have a ‘req‘ (request) object in Express JS which is used to represent the incoming HTTP request that consists of data like parameters, query strings, and also the request body. Along with this, we have ‘res‘ (response) which is used to send the HTTP response to the client which allows the modification of headers and consists of status codes, and resources.

Similar Reads

Prerequisites

Node JS Express JS...

How are req and res Objects Useful?

Both the objects ‘req‘ and ‘res‘ are responsible for handling the HTTP requests and responses in the web applications. Below are some of the points which describe the benefits of these objects:...

Steps to use req and res objects in Express

Step 1: In the first step, we will create the new folder as an http-objects by using the below command in the VScode terminal....

Contact Us