Fastify Node.js中如何正确获取URL路径参数z/x/y?
Fastify中获取URL路径参数的正确方式
你尝试从URL http://localhost:3001/query_tile/10/544/336 提取z、x、y值,但当前代码报错:
{"statusCode":500,"error":"Internal Server Error","message":"Cannot destructure property 'z' of 'request.body' as it is undefined."}
你的错误代码如下:
interface BodyType { z : string x : string y : string } fastify.get('/query_tile/:z/:x/:y', async (request : FastifyRequest<{ Body: BodyType }>, reply) => { const { z, x, y } = request.body; console.log(z,x,y, request.body) // .... })
问题原因
你混淆了路径参数和请求体的概念:
- URL中
:z/:x/:y属于路径参数,存储在request.params对象中 request.body仅用于POST/PUT等携带请求体的请求,GET请求不存在请求体,因此request.body为undefined
正确实现方式
修改类型定义和参数获取逻辑,从request.params中提取值:
// 定义路径参数的类型 interface ParamsType { z : string x : string y : string } fastify.get('/query_tile/:z/:x/:y', async (request : FastifyRequest<{ Params: ParamsType }>, reply) => { // 从request.params中解构z、x、y const { z, x, y } = request.params; console.log(z, x, y); // 输出:10 544 336 // 如果需要转为数字类型 const zNum = parseInt(z, 10); const xNum = parseInt(x, 10); const yNum = parseInt(y, 10); // 后续业务逻辑 })
内容的提问来源于stack exchange,提问作者pcace
相关产品推荐
相关产品推荐

