【发布时间】:2022-11-21 15:51:13
【问题描述】:
我试图在 Express 的 Request 对象中添加一个用户对象作为自定义属性,但出现以下错误:
Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'
这是我在中间件函数中的代码:
// Authenticate person/user through the database.
const person = new Person(username, password);
const user = await authenticate(person); // ORM => read DB
if (!user) {
return res
.status(401)
.json({ message: "Invalid Authentication Credentials" });
}
// attach user to request object
req.user = user; // <= HERE is my problem
next();
如何将此自定义属性添加到请求中?
【问题讨论】:
-
请显示更多代码上下文,以便我们可以看到此代码位于其中的内容。而且,如果这是特定于 TypeScript 的错误,那么您将不得不做一些 TypeScript 的事情,以便允许将自定义属性添加到仅具有 TypeScript 所关注的某些属性的对象。这是使用类型化系统时涉及的额外工作。有关详细信息,请参阅此article。
标签: node.js typescript express authentication