Skip to content

Sending Responses

Every request is a journey. The client (browser/phone) drove all the way to your server to get something. If you don’t give them a return trip, they just sit there… waiting… forever.

In Express, the Response Object (res) is how we load the cargo and send the vehicle back home.

Sci-fi loading dock loading a glowing blue data container onto awaiting transport vehicle.

Fig 1: The Loading Dock. Preparing the Payload.

We typically send data back in one of two ways:

  1. res.send(body): The general purpose tool. It automatically detects the content type.
    • Pass it a string? Sends text/html.
    • Pass it an object/array? Sends application/json.
  2. res.json(body): The specialist. It forces the response to be JSON. It is safer ensuring that null or undefined are treated as valid JSON values, not errors.
// The Generalist (res.send)
app.get('/', (req, res) => {
res.send('<h1>Welcome to the Dock</h1>'); // Content-Type: text/html
});
// The Specialist (res.json) - PREFERRED for APIs
app.get('/data', (req, res) => {
// Automatically stringifies the object
res.json({ status: 'loaded', cargo: ['box1', 'box2'] });
});

Express Response Basics - Demo Repo

Express API: res.send()

⏭ The Manifest

Before we leave the dock, we need to stamp the package with a Status Code.