Status Codes
Part of the Express Basics section of Coddy's Node.js journey. Lesson 7 of 20.
A program reads the status code before the body, so an error sent with 200 looks like a success.
app.get('/api/loans', (req, res) => {
if (!req.query.member) {
res.status(400).json({ error: 'Say which member' });
return;
}
res.json(loansOf(req.query.member));
});res.status(code) sets the status and returns res, so .json(...) can follow on the same line. return stops the function after the error. The codes you meet most:
- 200: it worked (the default).
- 201: something was created.
- 400: the request is wrong, like a missing field.
- 404: nothing is at that path or id.
- 500: the server failed.
Challenge
EasyAn unknown id on GET /api/recipes/:id answers 404 with { "error": "No such recipe" }.
Send GET /api/recipes/99 and GET /api/recipes/abc, then GET /api/recipes/3, and compare the statuses.
Try it yourself
import express from 'express';
import { recipes } from './data.js';
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to Recipe Box');
});
// type('text') sends plain text, so each title shows on its own line.
app.get('/recipes', (req, res) => {
const { tag } = req.query;
const list = tag ? recipes.filter((recipe) => recipe.tags.includes(tag)) : recipes;
res.type('text').send(list.map((recipe) => recipe.title).join('\n'));
});
app.get('/recipes/:id', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).send('No such recipe');
return;
}
res.send(recipe.title);
});
app.get('/api/recipes', (req, res) => {
res.json(recipes);
});
app.get('/api/recipes/:id', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).send('No such recipe');
return;
}
res.json(recipe);
});
app.get('/about', (req, res) => {
res.send('Recipe Box collects family recipes.');
});
app.listen(3000, () => {
console.log('Recipe Box is running on port 3000');
});