博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Nest.js 添加中间件
阅读量:6909 次
发布时间:2019-06-27

本文共 1688 字,大约阅读时间需要 5 分钟。

创建中间件 logger.middleware.ts

import { Injectable, NestMiddleware, MiddlewareFunction } from '@nestjs/common'@Injectable()export class LoggerMiddleware implements NestMiddleware {  resolve(...args: any[]): MiddlewareFunction {    return (req, res, next) => {      console.log('收到请求:');      next();    }  }}

使用中间件 app.module.ts

import { Module, NestModule, MiddlewareConsumer, RequestMethod } from '@nestjs/common';import { AppController } from './app.controller';import { AppService } from './app.service';import { LoggerMiddleware } from './logger.middleware'@Module({  imports: [],  controllers: [AppController],  providers: [AppService],})export class AppModule implements NestModule {  configure(consumer: MiddlewareConsumer) {    consumer      .apply(LoggerMiddleware)      .forRoutes({        path: '*',        method: RequestMethod.ALL,       })  }}

函数 中间件

export function logger(req, res, next) {  console.log(`Request...`);  next();};---configure(consumer: MiddlewareConsumer) {    consumer      .apply(logger)      .forRoutes(CatsController);  }

全局使用

function logger(req, res, next) {  console.log('收到请求');  next();}const app = await NestFactory.create(ApplicationModule);app.use(logger);await app.listen(3000);

5到6的修改

// Before@Injectable()export class LoggerMiddleware implements NestMiddleware { resolve(...args: any[]): MiddlewareFunction {   return (req: Request, res: Response, next: Function) => {     console.log('Request...');     next();   }; }}// After@Injectable()export class LoggerMiddleware implements NestMiddleware {  use(req: Request, res: Response, next: Function) {    console.log('Request...');    next();  }}

转载于:https://www.cnblogs.com/ajanuw/p/9572917.html

你可能感兴趣的文章
ubuntu12.04 修改登陆用户 为root
查看>>
silverlight开发实例(Prism+MVVM+RIA)(二)--创建shell及用户登录
查看>>
jsp中将后台传递过来的json格式的list数据绑定到下拉菜单select
查看>>
Project Euler 85 :Counting rectangles 数长方形
查看>>
MYSQL查询某字段中以逗号分隔的字符串的方法
查看>>
Excel设置下拉菜单并隐藏下拉菜单来源单元格内容
查看>>
Java8初体验(二)Stream语法详解
查看>>
微服务架构——不是免费的午餐
查看>>
基于HTML5的Web SCADA工控移动应用
查看>>
VS 2015相当不错的功能:C#交互窗口
查看>>
hive复杂类型与java类型的对应
查看>>
[Ubuntu] ubuntu10.04系统维护之Wine的安装
查看>>
iOS获取UIView上某点的颜色值
查看>>
cocos2d-x 3.0 android mk文件 之 自己主动遍历*.cpp文件
查看>>
python数字图像处理(7):图像的形变与缩放
查看>>
设计模式-观察者模式(上)<转>
查看>>
RabbitMQ 集群与高可用配置
查看>>
Java学习——何为JNDI
查看>>
Android IOS WebRTC 音视频开发总结(六二)-- 大数据解密国外实时通讯行业开发现状...
查看>>
CSharpGL(11)用C#直接编写GLSL程序
查看>>