小编Yos*_*shi的帖子

如何使用 express 中间件处理类型?

我在 Node.js 中使用 Typescript。当您使用 Express 中间件时,您经常会转换 Request 对象。但是,使用 Typescript,我们无法跟踪 Request 对象是如何转换的。如果知道之前通过的中间件,有没有办法从中找出请求的类型?如果在 express 中不可能,我想找到另一个可能的框架。在 Nest ( https://github.com/kamilmysliwiec/nest ) 中可以吗?

示例代码

import { Request, Response, NextFunction } from 'express';

function userMiddleware(req: Request & User, res: Response, next: NextFunction) {
    req.user = {
        id: 'user_id',
    };
    next();
}

interface User {
    user: {
        id: string;
    }
}

interface Middleware {
    <T>(req: Request & T, res: Response, next: NextFunction): void;
}

class Controller {
    middleware = [userMiddleware];

    get = new GetMethod(this.middleware);

    post = (req: …
Run Code Online (Sandbox Code Playgroud)

node.js express typescript

14
推荐指数
1
解决办法
3475
查看次数

标签 统计

express ×1

node.js ×1

typescript ×1