The Response Object (res)

The res object represents the HTTP response that an Express app sends when it gets an HTTP request.

Commonly Used Methods

MethodPurposeExample
res.send()Send a response of various typesres.send('Done')
res.json()Send a JSON response (Best for APIs)res.json({ id: 1 })
res.status()Set the HTTP status coderes.status(404)
res.render()Render a view templateres.render('index')
res.redirect()Redirect to a different URLres.redirect('/login')
res.sendFile()Send a file as an octet streamres.sendFile(path)

Chaining Methods

You can chain methods together to set a status and send data in one line.

app.get('/api/users', (req, res) => {
  res.status(201).json({ message: 'User created' });
});

Redirections

Use res.redirect() to move users between pages, such as after a successful form submission.

app.get('/old-page', (req, res) => {
  res.redirect(301, '/new-page'); // Permanent redirect
});
Best Practice: Always use res.json() when building APIs, as it automatically sets the Content-Type to application/json.