前文参考:
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测试,后端可以看到请求方法与路径的打印文章来源:https://www.toymoban.com/news/detail-832442.html
文章来源地址https://www.toymoban.com/news/detail-832442.html
到了这里,关于NestJS入门6:日志中间件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!