Menu
CoddyTech

Обработчик 404

Часть раздела Основы Express путешествия по Node.js на Coddy. Урок 14 из 20.

Express отвечает на неизвестный путь своей страницей Cannot GET /x, которая не подходит ни для вашего сайта, ни для вашего API.

app.use((req, res) => {
    res.status(404).send('No forecast here. Try /weather/oslo');
});

Промежуточное ПО без пути запускается для каждого запроса, который до него доходит. Разместите его после всех маршрутов и после express.static: запросы, на которые они ответили, сюда не доходят, поэтому оно видит только те запросы, на которые никто не ответил. Оно отвечает на запрос, поэтому ему не нужен next.

req.path — это путь без строки запроса, поэтому req.path.startsWith('/api/') позволяет отличить вызов API от страницы.

challenge icon

Задание

Легко
  • Для пути в /api/, на который нет ответа, возвращается 404 с { "error": "Not found" }.
  • Для любого другого такого пути возвращается HTML-страница с кодом 404 и текстом Page not found.

Отправь GET /api/nope, открой /nope в режиме просмотра страницы, затем отправь GET /api/recipes/1.

Попробуйте сами

import express from 'express';
import { randomUUID } from 'node:crypto';
import { recipes } from './data.js';

const app = express();

app.use((req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next();
});

app.use((req, res, next) => {
    res.set('X-Request-Id', randomUUID());
    next();
});

app.use(express.json());

app.use(express.static('public'));

const escapeHtml = (text) =>
    text
        .replaceAll('&', '&')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;');

app.get('/', (req, res) => {
    const items = recipes.map((r) => `<li><a href="/recipes/${r.id}">${escapeHtml(r.title)}</a></li>`);
    res.send(`<link rel="stylesheet" href="/style.css"><h1>Recipe Box</h1><ul>${items.join('')}</ul>`);
});

// type('text') отправляет обычный текст, поэтому каждый заголовок выводится на отдельной строке.
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).json({ error: 'No such recipe' });
        return;
    }
    res.json(recipe);
});

app.post('/api/recipes', (req, res) => {
    const { title, tags } = req.body;
    if (!title) {
        res.status(400).json({ error: 'A recipe needs a title' });
        return;
    }
    const recipe = { id: recipes.length + 1, title, tags: tags ?? [] };
    recipes.push(recipe);
    res.status(201).json(recipe);
});

app.get('/about', (req, res) => {
    res.send('Recipe Box collects family recipes.');
});

app.get('/menu', (req, res) => {
    res.redirect(301, '/recipes');
});

app.get('/menu/:id', (req, res) => {
    res.redirect(301, `/recipes/${req.params.id}`);
});

app.listen(3000, () => {
    console.log('Recipe Box is running on port 3000');
});

Все уроки раздела Основы Express