赞
踩
前文参考:
nest g middleware logger middleware
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();
- }
- }
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('*');
使用postman或swagger测试,后端可以看到请求方法与路径的打印
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。