DEV Community

Jeferson Eiji
Jeferson Eiji

Posted on Originally published at dev.to

Understanding the Role of Request and Response Objects in Express.js

In Express.js, the request (req) and response (res) objects are essential for handling HTTP transactions between a client and a server. Here's what you should know:

Request Object (req)

  • Represents the HTTP request made by the client
  • Contains details such as:
    • URL parameters (req.params)
    • Query strings (req.query)
    • Headers (req.headers)
    • Request body (req.body)

Example:

app.get('/users/:id', (req, res) => {
  // Access URL parameter
  const userId = req.params.id;
  res.send(`User ID is ${userId}`);
});
Enter fullscreen mode Exit fullscreen mode

Response Object (res)

  • Facilitates sending a response back to the client
  • Methods include:
    • res.send() for sending a response body
    • res.json() for JSON data
    • res.status() to set response status codes
    • res.redirect() to redirect clients

Example:

app.post('/login', (req, res) => {
  const { username, password } = req.body;
  if(username === 'admin') {
    res.status(200).json({ message: 'Login successful' });
  } else {
    res.status(401).send('Unauthorized');
  }
});
Enter fullscreen mode Exit fullscreen mode

Summary

  • req lets you read data sent by the client
  • res allows you to construct and send an appropriate reply

Mastering these objects is central to building efficient Express.js servers.

Top comments (0)