Loading

Quipoin Menu

Learn • Practice • Grow

express-js / Express.js Request & Response
tutorial

Express.js Request & Response

Every time a client makes a request to your Express server, two objects are created: the **Request** object (`req`) and the **Response** object (`res`). Understanding these objects is fundamental to building any Express application.

The Request Object (req)

The `req` object represents the HTTP request and contains properties for the request query string, parameters, body, HTTP headers, and more.

Property/MethodDescription
req.paramsRoute parameters (e.g., `/users/:id` gives `req.params.id`).
req.queryQuery string parameters (e.g., `?sort=asc` gives `req.query.sort`).
req.bodyRequest body (requires body-parser middleware).
req.headersHTTP headers object.
req.methodHTTP method (GET, POST, etc.).
req.urlRequest URL.
req.pathPath part of the URL (without query string).
req.ipClient's IP address.

Request Object Examples
app.get('/users/:id', (req, res) => {
  console.log('Params:', req.params); <!-- { id: '123' } -->
  console.log('Query:', req.query); <!-- { sort: 'asc' } for /users/123?sort=asc -->
  console.log('Method:', req.method); <!-- GET -->
  console.log('Headers:', req.headers.authorization); <!-- Bearer token... -->
  res.send('User page');
});

The Response Object (res)

The `res` object represents the HTTP response that your Express app sends when it gets an HTTP request. It has methods for sending data back to the client.

MethodDescription
res.send()Send a response (string, object, array, buffer).
res.json()Send a JSON response.
res.status()Set HTTP status code.
res.sendStatus()Set status and send its string representation.
res.redirect()Redirect to another URL.
res.render()Render a view template.
res.set()Set response headers.
res.cookie()Set cookies.
res.clearCookie()Clear cookies.

Response Object Examples
app.get('/text', (req, res) => {
  res.send('Hello World'); <!-- Sends plain text -->
});

app.get('/json', (req, res) => {
  res.json({ message: 'Hello World', status: 'success' });
});

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

app.get('/redirect', (req, res) => {
  res.redirect('/new-page');
});

app.get('/download', (req, res) => {
  res.download('./files/report.pdf');
});

Chaining Response Methods

Most response methods are chainable:
app.get('/user', (req, res) => {
  res
    .status(200)
    .set('X-Custom-Header', 'Hello')
    .cookie('visited', 'true')
    .json({ name: 'John' });
});

Two Minute Drill

  • `req` object contains request information: params, query, body, headers, method, etc.
  • `res` object sends responses: `res.send()`, `res.json()`, `res.status()`, etc.
  • Use `req.params` for route parameters, `req.query` for query strings.
  • Always set appropriate status codes (200, 201, 400, 404, 500, etc.).
  • Response methods can be chained for cleaner code.

Need more clarification?

Drop us an email at career@quipoinfotech.com