node.js - 从 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块。
解决方案
问题是您的转换(<any>+req)
转换为(+req)
解析req
为数字的转换 - 因此您没有.params
要纠正您的问题,请替换(<any>+req)
为(req as any)
或(<any>req)
推荐阅读
- html - Custom URL Protocol with arguments is looking for the arguments inside Mozilla's directory
- python - Python Discord.py 客户端语法无效
- windows - git: 'ssh-keygen' 不是 git 命令。见'git --help'
- html - 旋转木马渐变黑色效果
- python - python - 如何在空格键上暂停和取消暂停程序
- php - 循环以在 Wordpress 中插入带有 3 张带有偏移量的卡片的新轮播项目
- c# - “X 之一”对一实体关系
- android - Error on Android build: "aapt2: error=2, No such file or directory"
- python - Changing multiple column values to binary values
- windows - 如何确定应用程序使用 OllyDbg 终止的方式?