查询字符串
本课属于 Coddy Node.js 学习旅程的“Express 基础”单元。第 5 课,共 23 课。
列表页面通常需要一些选项,比如要显示哪些食谱。为每个选项都新建一个路由会太多。
app.get('/books', (req, res) => {
const { author } = req.query;
res.send(author ? 'Books by ' + author : 'All books');
});查询字符串是 URL 中 ? 后面的部分,Express 会将它放在对象 req.query 中。const { author } = req.query 是 const author = req.query.author 的简写。GET /books?author=Austen 会得到 req.query.author === 'Austen'。如果没有 ?,它的值就是 undefined。多个选项用 & 连接:/books?author=Austen&year=1813。
路由参数是路径的一部分,用来指明某个对象。查询选项用于筛选或排序列表,也可以省略。
挑战
简单访问者想只查看纯素食谱或晚餐食谱,而不想为每个标签都打开一个新页面。
- 在
server.js中修改/recipes路由。从查询字符串中读取tag选项。data.js中的每个食谱都有一个tags列表,例如['vegan', 'soup']。 - 如果提供了标签,就只发送
tags中包含该标签的食谱标题,每行一个标题,和当前路由的做法一样。 - 如果没有提供标签,就像之前一样发送所有标题。
- 如果没有食谱包含该标签,就发送状态码为 200 的空响应。
试试看:按“运行”,然后发送 /recipes?tag=vegan。你应该会看到两行:Tomato Soup 和 Lentil Curry。发送 /recipes?tag=dinner:Lentil Curry 和 Fish & Chips。发送 /recipes?tag=dessert:响应为空,因为没有食谱包含该标签。发送 /recipes:查看全部四个标题。
亲手试试
import express from 'express';
import { recipes } from './data.js';
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to Recipe Box');
});
// type('text') 发送纯文本,因此每个标题都会单独占一行。
app.get('/recipes', (req, res) => {
res.type('text').send(recipes.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('/about', (req, res) => {
res.send('Recipe Box collects family recipes.');
});
app.listen(3000, () => {
console.log('Recipe Box is running on port 3000');
});
Express 基础中的所有课
自己练习: Express 在线编辑器