Handle HTTP Responses: Status Codes, Headers, and JSON Data
🎯 Introduction
By the end of this article, you will be able to return appropriate status codes, headers, JSON, and responses without a body.
📤 Return JSON data
Create response-server.mjs:
import express from 'express';
const app = express();
Add a query endpoint:
app.get('/users/1', (req, res) => {
res.json({ id: 1, name: 'Ming' });
});
Visiting /users/1 returns status 200 and {"id":1,"name":"Ming"}. res.json sets the JSON media type and serializes the object automatically. Do not call JSON.stringify first, or you may return a JSON string as the data.
🚦 Set the status code for successful creation
Creation endpoints usually return 201. This example demonstrates the response with a fixed record; it does not write to a database:
app.post('/users', (req, res) => {
res.status(201).json({ id: 2, name: 'Hong' });
});
status(201) sets the status, and json sends the body and ends the response. Calling status alone does not send anything.
🧾 Set response headers before sending the body
To tell the client where the new resource is located, replace the previous POST route with:
app.post('/users', (req, res) => {
res.location('/users/2');
res.status(201).json({ id: 2, name: 'Hong' });
});
The response now includes Location: /users/2. location only sets the address; it does not turn this 201 response into a redirect. Headers cannot be changed after the body is sent, so set them before calling json.
🫙 A successful deletion can omit the body
Return 204 when the client only needs to know that the operation completed:
app.delete('/users/1', (req, res) => {
res.status(204).end();
});
This example only demonstrates a success response; it does not delete data. A 204 response has no body, so clients should not attempt JSON parsing. If you need to return information after deletion, define a response using 200 and JSON instead.
⚠️ Use an appropriate failure status
This example demonstrates 404 for a user known to be missing:
app.get('/users/999', (req, res) => {
res.status(404).json({ error: 'User not found' });
});
Both the status and body indicate failure. Do not keep status 200 while only describing failure in the body. Each request gets one response. Exit the current control flow after a branch sends it to avoid sending again later.
🧪 Inspect the status, headers, and body
Place the listener at the end of the file:
app.listen(3000, '127.0.0.1');
Run node response-server.mjs, then send a request from another terminal:
curl -i -X POST http://127.0.0.1:3000/users
Expect 201 and user JSON. After applying the Location example, you will also see that header. Requesting GET /users/999 returns 404; DELETE /users/1 returns 204 without a body.
❓ Questions and Answers
Q1: Must a JSON response use a data field?
No. The API contract defines its structure. Keep it consistent within the project.
Q2: Do I need to call end after res.json?
No. json already sends and ends the response.
Q3: Can database records be returned unchanged?
Select only fields that may be exposed. Never return internal data such as password records to clients.
🧪 Practice
Add a /users/3 query endpoint and inspect the status and body for both success and a missing resource.
// Write your code here
