【问题标题】:How to add custom properties on the Request object in Express + TypeScript?如何在 Express + TypeScript 中的 Request 对象上添加自定义属性?
【发布时间】: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


【解决方案1】:

我认为执行此操作的标准方法是扩展 Express 导出的 Response 接口并将您的数据声明为 Locals 通用类型的一部分。

@types/express/index.d.ts@第 127 行:

export interface Response<ResBody = any, Locals extends Record<string, any> = Record<string, any>>
        extends core.Response<ResBody, Locals> {}

因此,您可以创建一个 Type 来代替 Locals 泛型的默认值,如下所示:

import type { Response, Request, NextFunction } from 'express';
import type { User } from './models'; // Or wherever it is, obviously.
type MyLocals = { user?: User; };
type MyResponse = Response<any, MyLocals>

// Using the `MyResponse` type is as simple as setting the type of `res` to be `MyResponse`, e.g.:

async function doSomeWork (req: Request, res: MyResponse, next: NextFunction): Promise<void> {
  console.log(res.locals.user); // undefined | User
}

还有一些其他方法可以实现这一点,但这是我在使用 Typescript + Express 时一直在做的事情。

【讨论】:

    猜你喜欢
    • 2020-05-18
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多