前文参考:
NestJS入门1
NestJS入门2:创建模块
NestJS入门3:不同请求方式前后端写法
NestJS入门4:MySQL typeorm 增删改查
NestJS入门5:加入Swagger
1. 安装
nest g middleware logger middleware
2. logger.middleware.ts修改
logger.middleware.ts修改为:
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';@Injectable()
export class LoggerMiddleware implements NestMiddleware {use(req: Request, res: Response, next: () => void) {const {method, path} = req;console.log(`${method} ${path}`);next();}
}
3. app.modules.ts修改
app.modules.ts修改为:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from "./user/user.module";
import { TypeOrmModule } from "@nestjs/typeorm";
import { LoggerMiddleware } from './middleware/logger/logger.middleware';
import { MiddlewareBuilder } from '@nestjs/core';@Module({imports: [UserModule,TypeOrmModule.forRoot({type: "mysql",host: "localhost",port: 3306,username: "root",password: "root",database: "user", //数据库名称entities: ["dist/**/*.entity{.ts,.js}"], //扫描本项目中.entity.ts或者.entity.js的文件synchronize: true,}),],controllers: [AppController],providers: [AppService],
})
export class AppModule {configure(consumer: MiddlewareBuilder){consumer.apply(LoggerMiddleware).forRoutes('user');}}
可改为星号通配符,表示任意路由
consumer.apply(LoggerMiddleware).forRoutes('*');
4. 测试
使用postman或swagger测试,后端可以看到请求方法与路径的打印