0

我正在使用 NestJS 项目,并希望记录每个请求。我在我的 REST API 中使用Fastify 。我制作了一个用于获取请求正文的嵌套中间件:

import { HttpException, Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
        use(req: Request, res: Response, next: NextFunction) {
                const { httpVersion, headers, method, baseUrl, params, query, body } = req;
                // body is Undefined!
                console.log('Request Body...', body);                
                next();
        }
}

当我将日志打印到控制台时,我得到了输出undefined

app.module.ts:

export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .forRoutes('*');
  }
}

main.ts:

import { NestFactory } from '@nestjs/core';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter()
  );
  await app.listen(3000);
}
bootstrap()
4

0 回答 0