Menu
CoddyTech

Status Codes

Part of the Express Basics section of Coddy's Node.js journey. Lesson 7 of 23.

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 icon

Challenge

Easy

A program that reads your API checks the status code first, then the body. Make the not-found case clear to both.

  1. In server.js, in the /api/recipes/:id route, change what happens when no recipe has the id. Keep the status 404, but send this JSON instead of the text: {"error": "No such recipe"}
  2. An id that is not a number, like abc, matches no recipe either. It gets the same 404 and the same JSON.

Try it: Press Run and send /api/recipes/99. You should see status 404 and {"error":"No such recipe"}. Send /api/recipes/abc: the same 404 and JSON. Send /api/recipes/3: status 200 and the Lentil Curry recipe.

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');
});

All lessons in Express Basics

Practice on your own: Express playground