0
0
Expressframework~5 mins

Method chaining on response in Express

Choose your learning style9 modes available
Introduction

Method chaining on response lets you write cleaner code by linking multiple response actions together. It makes your server replies easier to read and write.

When you want to set the status and send data in one line.
When you want to set headers and then send a response quickly.
When you want to customize the response before sending it without extra variables.
When you want to keep your code short and clear in route handlers.
Syntax
Express
res.status(code).set(headerObject).send(body)

You can chain many response methods because each returns the response object.

Common methods to chain: status(), set(), send(), json(), end().

Examples
Sends a 200 OK status with a simple text response.
Express
res.status(200).send('OK')
Sends a 404 status with a message saying the resource was not found.
Express
res.status(404).send('Not Found')
Sends a 201 Created status, sets the content type header, and sends JSON data.
Express
res.status(201).set({'Content-Type': 'application/json'}).json({id: 1})
Sets a custom header, then sends a 200 status with a message.
Express
res.set('X-Custom-Header', 'value').status(200).send('Done')
Sample Program

This Express app has three routes. Each uses method chaining on the response object to set status, headers, and send data in one line.

Express
import express from 'express';

const app = express();

app.get('/hello', (req, res) => {
  // Send a 200 status with a greeting message
  res.status(200).set({'Content-Type': 'text/plain'}).send('Hello, world!');
});

app.get('/json', (req, res) => {
  // Send JSON data with 200 status
  res.status(200).json({message: 'This is JSON data'});
});

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

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Method chaining improves readability and reduces extra variables.

Time complexity is negligible; it's just calling methods on the response object.

Common mistake: forgetting to end the chain with a method that sends or ends the response, like send() or end().

Summary

Method chaining lets you combine response methods for cleaner code.

Use it to set status, headers, and send data in one line.

Always end the chain with a method that sends or ends the response.