首页 > 解决方案 > 从 GET 请求 url 获取参数值。“类型错误:无法读取属性”

问题描述

我只是想从获取请求的 url 路由参数中获取数据。我很确定我之前有这个工作,我没有改变任何东西。不知道发生了什么。

我一直在代码中放置 console.log 调用,只是为了看看会出现什么。但他们甚至从未被调用过。仅显示错误消息。

我正在使用邮递员,这是我正在发出的获取请求:

http://localhost:3333/users/accountidfind/1

这是我的 index.ts 文件中的路由器:

app.use('/users', userRouter);

这是错误来自的代码段:

userRouter.get('/accountidfind/:account_id', async (req: Request, resp: Response) => {
  //console.log(`retrieving user with id ${(<any>+req).params.account_id}`);
  const account_id = (<any>+req).params.account_id;
  
  

这是整个代码:

import { Request, Response } from "express";
      import * as express from "express";
      import * as userDao from "../dao/user-dao";
      
userRouter.get('/accountidfind/:account_id', async (req: Request, resp: Response) => {
      //console.log(`retrieving user with id ${(<any>+req).params.account_id}`);
      const account_id = (<any>+req).params.account_id;
      
      try {
        const user = await userDao.getUserById(account_id);
        if (user !== undefined) {
          resp.json(user);
        } else {
          resp.sendStatus(400);
        }
      } catch (err) {
        resp.sendStatus(500);
      }
    });

这是我得到的错误:

 (node:9532) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'account_id' of undefined
    at C:\GitFolder\roqq\server\routers\user-router.ts:95:41
    at Generator.next (<anonymous>)
    at C:\GitFolder\roqq\server\routers\user-router.ts:27:71
    at new Promise (<anonymous>)
    at __awaiter (C:\GitFolder\roqq\server\routers\user-router.ts:23:12)
    at C:\GitFolder\roqq\server\routers\user-router.ts:94:85
    at Layer.handle [as handle_request] (C:\GitFolder\roqq\server\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\GitFolder\roqq\server\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\GitFolder\roqq\server\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\GitFolder\roqq\server\node_modules\express\lib\router\layer.js:95:5)
(node:9532) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 6)

我也不明白错误消息是如何说异步函数没有catch块,而确实有一个catch块。

标签: node.jstypescriptexpressurl-parametersget-request

解决方案


问题是您的转换(<any>+req)转换为(+req)解析req为数字的转换 - 因此您没有.params

要纠正您的问题,请替换(<any>+req)(req as any)(<any>req)

类型断言文档


推荐阅读