fastify 路由无法解析为变量(req.params 为空)

问题描述 投票:0回答:1

我正在尝试运行一个小型 fastify(typescript 和 nodejs)服务器。

fastify.get('/query_tile/:z/:x/:y', async (req, reply) => {
    const t0 = performance.now()

    const { z, x, y }: { z: string, x: string, y: string } = req.params;
    const useCache = req.query.useCache !== 'false'; // use cache by default
    // ......
})

来自 fastify 文档。 我遇到的问题是 z,x,y 没有定义:

TSError: ⨯ Unable to compile TypeScript:
src/app.ts:54:11 - error TS2739: Type '{}' is missing the following properties from type '{ z: string; x: string; y: string; }': z, x, y

54     const { z, x, y }: { z: string, x: string, y: string } = req.params;
             ~~~~~~~~~~~
src/app.ts:55:32 - error TS2339: Property 'useCache' does not exist on type 'unknown'.

55     const useCache = req.query.useCache !== 'false'; // use cache by default
                                  ~~~~~~~~

我在这里做错了什么?

node.js typescript fastify
1个回答
0
投票

在尝试解构 req.params 并在 Fastify 路由处理程序中访问 req.query 时,您似乎遇到了 TypeScript 类型检查错误。错误消息表明 TypeScript 无法推断 req.params 和 req.query 的正确类型,导致 z、x、y 和 useCache 无法识别或类型未知。

要解决这些问题,您可以在 Fastify 路由处理程序中显式定义 req.params 和 req.query 的类型。以下是修改代码的方法:

import { FastifyRequest, FastifyReply } from 'fastify';
  fastify.get('/query_tile/:z/:x/:y', async (req: 
  FastifyRequest, reply: 
    FastifyReply) => {
    const { z, x, y }: { z: string; x: string; y: string } = 
    req.params as { z: string; x: string; y: string };
    const useCache: boolean = req.query.useCache !== 'false'; // use cache by default

// Now you can use z, x, y, and useCache in your logic

const t0 = performance.now();

// Example response
return { z, x, y, useCache };

});

© www.soinside.com 2019 - 2024. All rights reserved.