Sending Responses

Use res.send, res.json and res.status to reply to the client.

Syntaxres.status(201).json({ ... })

The res object sends the reply. The most common methods:

  • res.send() — send text, HTML or a buffer.
  • res.json() — send a JavaScript object as JSON.
  • res.status(code) — set the HTTP status code (chainable).
  • res.end() — end the response with no body.

You can send only one response per request. Calling two send methods causes an error.

Example

Example · javascript
app.get('/text', (req, res) => res.send('Plain text'));

app.get('/data', (req, res) => {
  res.json({ name: 'Express', stars: 5 });
});

app.post('/create', (req, res) => {
  res.status(201).json({ created: true });
});

When to use it

  • An API endpoint calls res.json() to serialise a JavaScript object into a JSON response with the correct Content-Type header automatically.
  • A download endpoint uses res.download() to send a file with a Content-Disposition: attachment header so the browser saves it to disk.
  • A server-rendered page handler calls res.render('home', data) to let the view engine produce and send HTML.

More examples

res.send vs res.json

Shows three common response methods: plain text, JSON, and an empty response with a status code.

Example · js
// Plain text
app.get('/text', (req, res) => res.send('Hello'));

// JSON with correct Content-Type
app.get('/json', (req, res) => res.json({ status: 'ok' }));

// Empty 204
app.delete('/item', (req, res) => res.status(204).send());

res.status chaining

Chains res.status() with res.json() to set a non-200 HTTP status and send a JSON body in one statement.

Example · js
app.post('/users', (req, res) => {
  const { name } = req.body;
  if (!name) {
    return res.status(400).json({ error: 'name is required' });
  }
  res.status(201).json({ created: true, name });
});

res.download for file delivery

Sends a file as an attachment using res.download(), triggering a browser save dialog, and handles missing files.

Example · js
const path = require('path');

app.get('/reports/:filename', (req, res) => {
  const file = path.join(__dirname, 'reports', req.params.filename);
  res.download(file, req.params.filename, (err) => {
    if (err) res.status(404).json({ error: 'File not found' });
  });
});

Discussion

  • Be the first to comment on this lesson.