Request and Response objects


In Node.js and Express.js, the Request and Response objects are essential components of the request-response cycle in web applications. They allow you to handle incoming requests and send responses back to the client. Here’s a detailed look at both:

Request Object (req)

The Request object represents the incoming HTTP request and contains information about the request sent by the client. In Express.js, this object is an instance of the http.IncomingMessage class.

Key Properties and Methods

  1. req.method: The HTTP method used for the request (e.g., GET, POST, PUT, DELETE).

    console.log(req.method); // 'GET'
  2. req.url: The URL of the request.

    console.log(req.url); // '/api/data'
  3. req.headers: An object representing the headers of the request.

    console.log(req.headers['content-type']); // 'application/json'
  4. req.query: An object containing query parameters from the URL (e.g., /search?term=express).

    console.log(req.query.term); // 'express'
  5. req.params: An object containing route parameters defined in the route path (e.g., /users/:id).

    app.get('/users/:id', (req, res) => { console.log(req.params.id); // User ID from the URL });
  6. req.body: An object containing the parsed body of the request, used with POST and PUT requests. It’s populated by middleware like express.json() or body-parser.

    app.use(express.json()); // Middleware to parse JSON bodies app.post('/submit', (req, res) => { console.log(req.body); // Parsed JSON body });
  7. req.cookies: An object containing cookies sent with the request, available if you use middleware like cookie-parser.

    const cookieParser = require('cookie-parser'); app.use(cookieParser()); app.get('/', (req, res) => { console.log(req.cookies); // { 'cookieName': 'cookieValue' } });
  8. req.file: An object containing information about a file uploaded through a form, available if you use middleware like multer.

    const multer = require('multer'); const upload = multer({ dest: 'uploads/' }); app.post('/upload', upload.single('file'), (req, res) => { console.log(req.file); // Information about the uploaded file });

Response Object (res)

The Response object represents the HTTP response that is sent back to the client. It allows you to control the response sent to the client.

Key Properties and Methods

  1. res.status(code): Sets the HTTP status code for the response.

    res.status(404).send('Not Found');
  2. res.send(body): Sends a response with the specified body. Can send strings, objects, arrays, or other types.

    res.send('Hello, world!'); res.send({ message: 'Success' });
  3. res.json(body): Sends a JSON response. Automatically sets the Content-Type header to application/json.

    res.json({ message: 'Success' });
  4. res.redirect(url): Redirects the client to a different URL.

    res.redirect('/login');
  5. res.set(header, value): Sets a header for the response.

    res.set('Content-Type', 'text/html');
  6. res.cookie(name, value, options): Sets a cookie on the client.

    res.cookie('username', 'JohnDoe', { maxAge: 900000, httpOnly: true });
  7. res.clearCookie(name, options): Clears a cookie from the client.

    res.clearCookie('username');
  8. res.end([body]): Ends the response process. Can optionally send a body.

    res.end('Goodbye!');

Example Usage

Here’s an example of handling a POST request and sending a response:

const express = require('express'); const app = express(); app.use(express.json()); // Middleware to parse JSON bodies app.post('/submit', (req, res) => { // Access request body const data = req.body; // Send a JSON response res.status(200).json({ message: 'Data received', data: data }); }); app.listen(3000, () => { console.log('Server running on port 3000'); });

In this example:

  • The request body is parsed and logged.
  • A JSON response is sent back to the client with a status code of 200.

Understanding these objects helps in handling HTTP requests and responses effectively in an Express.js application.