如何使用 TypeScript 扩展 Express Request 对象

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

我正在尝试向express的Request对象添加一个属性

首先创建一个中间件来验证会话,token带上companyId

import { verifyToken } from '../utils/jwt/jwt';

declare module 'express-serve-static-core' {
  interface Request {
    companyId: string;
  }
}

export const validateSession = (
  req: Request,
  res: Response,
  next: NextFunction
): void => {
  try {
    const jwtByUser = req.headers.authorization ?? null;
    const jwt = jwtByUser?.split(' ').pop();
    console.log(jwtByUser);
    console.log(jwt);

    const session = verifyToken(`${jwt}`);

    if (!session) {
      res.status(400).send('Invalid Token Session');
    }
    // Add userId and companyId to the request object
    // req.user.id = session.user.id;
    req.companyId = session.companyId;
    // req.user.role = session.user.role;
    // req.user.email = session.user.email;
    next();
  } catch (error) {
    res.status(400).send('Invalid Session');
  }
};

注意:我必须将与我放在index.d.ts上的内容相同的内容,否则我会出现错误req.companyId不存在

然后在 src/types index.d.ts 中创建一个文件

import 'express-serve-static-core';

declare module 'express-serve-static-core' {
  export interface Request {
    companyId: string;
  }
}

然后在我的 user.routes.ts 文件中添加中间件,最后在我的控制器中我应该能够使用这个属性。

这是我的路线

router.get('/', validateSession, usersController.getAllUsers);

这是我的控制器用户。控制器:

getAllUsers = async (req: Request, res: Response): Promise<void> => {
    const companyId = req.companyId;
    console.log(companyId);
    const filteredUser = await this.usersService.getAllUsers();

    handleResult(res, filteredUser, 200);
  };

我看过几篇文章,他们要求修改 tsconfig.json 文件,我已经尝试了数千种方法,但没有一个对我有用,我不断收到相同的错误。

当我使用 npm run dev 启动服务器时出现错误。

这是错误:

Error importing module: Error: ⨯ Unable to compile TypeScript: src/app/users/infrastructure/controller/user.controller.ts(60,27): error TS2339: Property 'companyId' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.

这是我的文件夹结构: x

javascript node.js typescript express tsconfig
1个回答
0
投票

我已经证实:

  1. 如果您复制,您的解决方案就可以正常工作
declare module 'express-serve-static-core' {
  export interface Request {
    companyId: string;
  }
}

进入您正在使用它的文件(例如您的控制器)

  1. 或者:添加一个index.d.ts文件,例如:
export * from "express-serve-static-core"

declare module 'express-serve-static-core' {
    interface Request {
      companyId: string;
    }
  }

根据这个答案:

https://stackoverflow.com/a/75810254/1068446

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