主题
路由参数与 Query
在 Fastify 中,可以通过 request.params
获取路径中的动态参数,通过 request.query
获取 URL 中的查询参数。
路由参数(Path Parameters)
使用冒号 :
来定义动态路径参数,例如:
js
fastify.get('/user/:id', async (request) => {
const { id } = request.params;
return { userId: id };
});
访问 /user/123
会返回:
json
{
"userId": "123"
}
支持多个参数:
js
fastify.get('/post/:postId/comment/:commentId', async (request) => {
const { postId, commentId } = request.params;
return { postId, commentId };
});
查询参数(Query Parameters)
用于处理 URL 中的 ?key=value
参数,例如:
js
fastify.get('/search', async (request) => {
const { keyword, page } = request.query;
return { keyword, page };
});
访问 /search?keyword=fastify&page=2
会返回:
json
{
"keyword": "fastify",
"page": "2"
}
Fastify 不限制参数个数和结构,但建议配合 Schema 做验证与类型转换。
混合使用
可以同时使用路径参数与查询参数:
js
fastify.get('/category/:id', async (request) => {
const { id } = request.params;
const { sort } = request.query;
return { id, sort };
});
请求 /category/5?sort=desc
返回:
json
{
"id": "5",
"sort": "desc"
}