Sending Responses
The Return Trip
Section titled “The Return Trip”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.
Fig 1: The Loading Dock. Preparing the Payload.
The Payload
Section titled “The Payload”We typically send data back in one of two ways:
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.
- Pass it a string? Sends
res.json(body): The specialist. It forces the response to be JSON. It is safer ensuring thatnullorundefinedare 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 APIsapp.get('/data', (req, res) => { // Automatically stringifies the object res.json({ status: 'loaded', cargo: ['box1', 'box2'] });});Extra Bits & Bytes
Section titled “Extra Bits & Bytes”Express Response Basics - Demo Repo
Express API: res.send()