You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 23:13:13