Status Codes and Errors
A status code is a number that reports how a request went. It travels with every response, beside the body.
Sending a status code
res.status sets the code on the response.
res.status(404).json({ error: 'Note not found' });Created means 201
A new note answers with 201.
res.status(201).json({ title: note.title, done: note.done });Checking the code
curl prints only the code for a missing note.
curl -s -o /dev/null -w "%{http_code}" http://localhost:3001/api/notes/000000000000000000000000Example
import express from 'express';
import mongoose from 'mongoose';
await mongoose.connect('mongodb://localhost:27017/notes');
const noteSchema = new mongoose.Schema({ title: String, done: Boolean });
const Note = mongoose.model('Note', noteSchema);
await Note.create({ title: 'Buy milk', done: false });
await Note.create({ title: 'Ship MERN', done: true });
await Note.create({ title: 'Read a book', done: false });
const app = express();
app.use(express.json());
app.get('/api/notes/:id', async (req, res) => {
const note = await Note.findById(req.params.id);
if (!note) {
res.status(404).json({ error: 'Note not found' });
return;
}
res.json({ title: note.title, done: note.done });
});
app.post('/api/notes', async (req, res) => {
const note = await Note.create(req.body);
res.status(201).json({ title: note.title, done: note.done });
});
const server = app.listen(0);
const port = server.address().port;
const base = `http://localhost:${port}`;
const missingId = new mongoose.Types.ObjectId();
const gone = await fetch(`${base}/api/notes/${missingId}`);
console.log(gone.status);
console.log(await gone.text());
const created = await fetch(`${base}/api/notes`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Water plants', done: false }),
});
console.log(created.status);
console.log(await created.text());
server.close();
await mongoose.disconnect();Key points
- 200 means the request worked.
- 201 means a new thing was created.
- 404 means the thing asked for is missing.
- res.status sets the code before the body is sent.
- The body still carries the detail, such as an error message.
In this example, the script connects to the notes database and saves the three notes. It builds an Express app with a GET route for one note and a POST route. The GET route answers 404 when the note is missing. The POST route answers 201 when a note is created. The script asks for a note that does not exist, then creates a new note. Each status prints first, then its body.
Note
A wrong code misleads the caller, even when the body is right.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A request asks for a note that does not exist. Which code should the API send?