前文参考:
1. 安装
bash
nest g middleware logger middleware
2. logger.middleware.ts修改
logger.middleware.ts修改为:
TypeScript
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修改为:
TypeScript
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');
}
}
可改为星号通配符,表示任意路由
TypeScript
consumer.apply(LoggerMiddleware).forRoutes('*');
4. 测试
使用postman或swagger测试,后端可以看到请求方法与路径的打印