Working with Request and Response Objects

Explore the request (req) and response (res) objects in Express.js and learn how to access request data, set response headers, and send data back to the client.


Mastering Express.js: Request and Response Objects

Working with Request and Response Objects

In Express.js, the request (req) and response (res) objects are fundamental to handling HTTP requests and sending responses back to the client. Understanding how to use these objects is crucial for building robust and dynamic web applications. These objects are passed as arguments to every route handler function you define.

Exploring the Request (req) Object

The req object represents the HTTP request and contains information about the client's request, such as:

  • Headers: Metadata about the request.
  • Query Parameters: Values passed in the URL after the question mark (?).
  • Route Parameters: Values extracted from the URL path based on route definitions.
  • Body: Data sent in the request body (often used for POST, PUT, and PATCH requests).

Accessing Request Data

Here are common ways to access data within the req object:

req.params: Accessing Route Parameters

Route parameters are defined in your route definition using colons (:). For example:

 app.get('/users/:userId', (req, res) => {
          const userId = req.params.userId;
          res.send(`User ID: ${userId}`);
        }); 

req.query: Accessing Query Parameters

Query parameters are appended to the URL after a question mark (?) and are key-value pairs. For example:

 app.get('/search', (req, res) => {
          const searchTerm = req.query.q;
          res.send(`Search term: ${searchTerm}`);
        }); 

req.body: Accessing Request Body Data

To access the request body, you typically need middleware like express.json() or express.urlencoded() to parse the incoming data. For example:

 const express = require('express');
        const app = express();

        app.use(express.json()); // Parse JSON request bodies
        app.use(express.urlencoded({ extended: true })); // Parse URL-encoded request bodies

        app.post('/submit', (req, res) => {
          const name = req.body.name;
          res.send(`Received name: ${name}`);
        }); 

req.headers: Accessing Request Headers

You can access request headers using req.headers, which is an object containing all the headers sent by the client.

 app.get('/profile', (req, res) => {
          const userAgent = req.headers['user-agent'];
          res.send(`User Agent: ${userAgent}`);
        }); 

Other useful properties:

  • req.method: The HTTP method used for the request (e.g., GET, POST, PUT, DELETE).
  • req.url: The URL requested by the client.
  • req.ip: The IP address of the client.
  • req.path: The path part of the request URL.

Exploring the Response (res) Object

The res object represents the HTTP response that your Express.js server will send back to the client. It provides methods for:

  • Setting Headers: Modifying response headers.
  • Sending Data: Sending various types of data (HTML, JSON, text, files).
  • Setting Status Codes: Setting the HTTP status code of the response.
  • Redirecting: Redirecting the client to a different URL.

Sending Data to the Client

Here are common methods for sending data back to the client using the res object:

res.send(): Sending Data

The res.send() method is the most basic way to send data. It can automatically set the Content-Type header based on the data type you're sending.

 app.get('/hello', (req, res) => {
          res.send('Hello, world!'); // Sends plain text
        });

        app.get('/html', (req, res) => {
          res.send('<h1>Hello from HTML!</h1>'); // Sends HTML
        }); 

res.json(): Sending JSON Data

The res.json() method sends data as JSON and automatically sets the Content-Type header to application/json.

 app.get('/data', (req, res) => {
          const data = { message: 'This is a JSON response' };
          res.json(data);
        }); 

res.sendFile(): Sending Files

The res.sendFile() method allows you to send files to the client.

 const path = require('path');

        app.get('/download', (req, res) => {
          const filePath = path.join(__dirname, 'public', 'example.txt'); // Assuming 'example.txt' is in a 'public' directory
          res.sendFile(filePath);
        }); 

res.render(): Rendering Templates

If you are using a templating engine (like EJS, Pug, or Handlebars), you can use res.render() to render a template and send the resulting HTML to the client.

 // Example with EJS
        app.set('view engine', 'ejs');

        app.get('/template', (req, res) => {
          res.render('index', { name: 'John' }); // Renders the 'index.ejs' template
        }); 

Setting Response Headers

You can set custom response headers using res.set() or res.header() (they do the same thing).

 app.get('/custom-header', (req, res) => {
          res.set('X-Custom-Header', 'My Value');
          res.send('Custom header set!');
        }); 

Setting Status Codes

You can set the HTTP status code of the response using res.status().

 app.post('/create', (req, res) => {
          // Logic to create a new resource...
          res.status(201).send('Resource created successfully!'); // 201 Created
        });

        app.get('/not-found', (req, res) => {
          res.status(404).send('Resource not found'); // 404 Not Found
        }); 

Redirecting the Client

You can redirect the client to a different URL using res.redirect().

 app.get('/redirect', (req, res) => {
          res.redirect('https://www.example.com');
        }); 

Chaining Response Methods

Express allows you to chain response methods together for more concise code:

 app.get('/chain', (req, res) => {
            res.status(200)
               .set('Content-Type', 'text/plain')
               .send('Chained response!');
          });