Node JS Request and Response Objects


In Node.js, particularly when using frameworks like Express.js, handling HTTP requests and responses is fundamental to building web applications and APIs. The request and response objects provide the means to interact with incoming requests and send responses back to the client. Here’s a detailed explanation of these objects:

1. Request Object (req)

The request object (req) contains information about the incoming HTTP request. It provides details such as the request headers, query parameters, URL, and body. In Express.js, the request object is an instance of the http.IncomingMessage class and includes additional properties and methods provided by Express.

1.1 Key Properties of req

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

    app.get('/', (req, res) => { console.log(req.method); // 'GET' });
  • req.url: The URL of the request.

    app.get('/', (req, res) => { console.log(req.url); // '/' });
  • req.headers: An object containing the request headers.

    app.get('/', (req, res) => { console.log(req.headers['user-agent']); // e.g., 'Mozilla/5.0 ...' });
  • req.query: An object containing query parameters from the URL.

    app.get('/search', (req, res) => { const query = req.query.q; res.send(`Search query: ${query}`); });
  • req.params: An object containing route parameters (dynamic values in the URL).

    app.get('/users/:userId', (req, res) => { const userId = req.params.userId; res.send(`User ID: ${userId}`); });
  • req.body: Contains data sent in the body of the request. This requires middleware such as express.json() or express.urlencoded() to parse the request body.

    app.post('/submit', express.json(), (req, res) => { const data = req.body; res.send(`Received data: ${JSON.stringify(data)}`); });
  • req.ip: The IP address of the client making the request.

    app.get('/', (req, res) => { console.log(req.ip); // e.g., '127.0.0.1' });
  • req.cookies: An object containing cookies sent by the client. Requires middleware like cookie-parser.

    const cookieParser = require('cookie-parser'); app.use(cookieParser()); app.get('/', (req, res) => { console.log(req.cookies); // e.g., { session_id: '12345' } });

2. Response Object (res)

The response object (res) is used to send data back to the client. It provides methods to set headers, send responses, and control the HTTP response.

2.1 Key Methods of res

  • res.send(): Sends a response to the client. Can be used to send strings, objects, arrays, or other types of data.

    app.get('/', (req, res) => { res.send('Hello, world!'); });
  • res.json(): Sends a JSON response. Automatically sets the Content-Type header to application/json.

    app.get('/data', (req, res) => { res.json({ key: 'value' }); });
  • res.status(): Sets the HTTP status code of the response.

    app.get('/error', (req, res) => { res.status(404).send('Page not found'); });
  • res.redirect(): Redirects the client to a different URL.

    app.get('/old', (req, res) => { res.redirect('/new'); });
  • res.render(): Renders a view template and sends the HTML response. Requires setting up a view engine like EJS or Pug.

    app.get('/', (req, res) => { res.render('index', { name: 'World' }); });
  • res.set(): Sets HTTP headers for the response.

    app.get('/', (req, res) => { res.set('X-Custom-Header', 'Value'); res.send('Header set'); });
  • res.sendFile(): Sends a file as a response. Requires the path to the file.

    app.get('/file', (req, res) => { res.sendFile(__dirname + '/public/file.txt'); });
  • res.end(): Ends the response without sending any data.

    app.get('/', (req, res) => { res.end(); // Ends the response });

3. Working with req and res Together

Here’s an example that demonstrates how to use both the request and response objects to handle a POST request and send a JSON response:

const express = require('express'); const app = express(); const port = 3000; // Middleware to parse JSON request bodies app.use(express.json()); app.post('/data', (req, res) => { const requestData = req.body; // Access data from the request body console.log('Received data:', requestData); // Send a JSON response back to the client res.status(200).json({ message: 'Data received successfully', receivedData: requestData }); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });

Summary

  • Request Object (req): Provides information about the incoming HTTP request, including method, URL, headers, query parameters, route parameters, body, and more.
  • Response Object (res): Used to send data back to the client, including sending text, JSON, files, setting headers, redirecting, and more.