404 处理程序
本课属于 Coddy Node.js 学习旅程的“Express 基础”单元。第 16 课,共 23 课。
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 调用和页面请求。
挑战
简单不存在的路径会显示 Express 默认的纯文本 Cannot GET 页面。把它替换成你自己的页面:API 返回 JSON,访客则看到友好的页面。
- 在
server.js中,所有路由和express.static之后,添加最后一个不带路径的app.use。已经得到响应的请求不会到达这里,因此它只会处理尚未处理的请求。 - 如果路径以
/api/开头,就返回状态码 404 和以下 JSON:{"error": "Not found"} - 对于其他路径,返回状态码 404 和一个包含文字
Page not found的 HTML 页面,例如<h1>Page not found</h1>。加一个返回主页的链接会更贴心。
试试看:按“运行”,然后发送 /api/nope。你应该会看到状态码 404 和 {"error":"Not found"}。发送 /nope:状态码为 404,显示的页面上写着 Page not found。发送 /api/recipes/1:状态码为 200,并显示 Tomato Soup,这说明你的路由仍然会优先处理请求。
亲手试试
import { escapeHtml } from './html.js';
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'));
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 基础中的所有课
自己练习: Express 在线编辑器