CPCODELAB
Express

Sending JSON and Status Codes

7 min read

Sending JSON and Status Codes

res.json() serialises any JavaScript value to JSON, sets the Content-Type: application/json header, and sends the response. You should chain .status() before it when you need a non-200 code.

js
app.post("/items", (req, res) => {
  const item = { id: 42, name: "Widget" }; // normally from DB
  res.status(201).json(item);
});

app.get("/items/:id", (req, res) => {
  const found = false; // replace with real lookup
  if (!found) {
    return res.status(404).json({ error: "Item not found" });
  }
  res.json({ id: req.params.id });
});

Common HTTP Status Codes

  1. 200 OK — successful GET or PATCH
  2. 201 Created — resource successfully created (POST)
  3. 204 No Content — successful DELETE with no body
  4. 400 Bad Request — client sent invalid data
  5. 401 Unauthorized — missing or invalid credentials
  6. 403 Forbidden — authenticated but not authorised
  7. 404 Not Found — resource does not exist
  8. 409 Conflict — e.g. duplicate email on signup
  9. 422 Unprocessable Entity — validation failed
  10. 500 Internal Server Error — unexpected server fault

Build a small ApiError class that carries a status code and message, then throw it from route handlers. Your error middleware catches it and calls res.status(err.status).json({ error: err.message }) in one place.

Ready to test yourself?
Practice Express— quiz & coding exercises