夜猫子的知识栈 夜猫子的知识栈
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《Web Api》
    • 《ES6教程》
    • 《Vue》
    • 《React》
    • 《TypeScript》
    • 《Git》
    • 《Uniapp》
    • 小程序笔记
    • 《Electron》
    • JS设计模式总结
  • 《前端架构》

    • 《微前端》
    • 《权限控制》
    • monorepo
  • 全栈项目

    • 任务管理日历
    • 无代码平台
    • 图书管理系统
  • HTML
  • CSS
  • Nodejs
  • Midway
  • Nest
  • MySql
  • 其他
  • 技术文档
  • GitHub技巧
  • 博客搭建
  • Ajax
  • Vite
  • Vitest
  • Nuxt
  • UI库文章
  • Docker
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

夜猫子

前端练习生
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《Web Api》
    • 《ES6教程》
    • 《Vue》
    • 《React》
    • 《TypeScript》
    • 《Git》
    • 《Uniapp》
    • 小程序笔记
    • 《Electron》
    • JS设计模式总结
  • 《前端架构》

    • 《微前端》
    • 《权限控制》
    • monorepo
  • 全栈项目

    • 任务管理日历
    • 无代码平台
    • 图书管理系统
  • HTML
  • CSS
  • Nodejs
  • Midway
  • Nest
  • MySql
  • 其他
  • 技术文档
  • GitHub技巧
  • 博客搭建
  • Ajax
  • Vite
  • Vitest
  • Nuxt
  • UI库文章
  • Docker
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • Node基础

  • 《MySQL》学习笔记

  • Midway

  • Nest

    • 开篇词
    • 学习理由
    • nest概念扫盲
    • 快速掌握 nestcli
    • 5种http数据传输方式
    • IoC 解决了什么痛点问题?
    • 如何调试 Nest 项目
    • Provider注入对象
    • 全局模块和生命周期
    • AOP 架构有什么好处?
    • 一网打尽 Nest 全部装饰器
    • Nest如何自定义装饰器
    • Metadata和Reflector
    • ExecutionContext切换上下文
    • Module和Provider的循环依赖处理
    • 如何创建动态模块
    • Nest和Express,fastify
    • Nest的Middleware
      • 创建 middleware:
      • 使用
      • 指定路由
      • @Next
      • 总结
    • RxJS和Interceptor
    • 内置Pipe和自定义Pipe
    • ValidationPipe验证post请求参数
    • 如何自定义 Exception Filter
    • 图解串一串 Nest 核心概念
    • 接口如何实现多版本共存
    • Express如何使用multer实现文件上传
    • Nest使用multer实现文件上传
    • 图书管理系统
    • 大文件分片上传
    • 最完美的 OSS 上传方案
    • Nest里如何打印日志
    • 为什么Node里要用Winston打印日志
    • Nest 集成日志框架 Winston
    • 通过Desktop学Docker也太简单了
    • 你的第一个 Dockerfile
  • 其他

  • 服务端
  • Nest
神说要有光
2025-03-10
目录

Nest的Middleware

Nest 里也有中间件 Middleware 的概念,它和 Express 的 Middleware 是一个东西么?

很像,但不一样。

上节讲过,Nest 并不是直接依赖于 Express,可以切换到别的 http 请求处理库,那 Nest 的特性肯定也不直接是 Express 里的。

我们创建个项目,边写边看:

nest new middleware-test
1

进入项目,执行:

nest g middleware aaa --no-spec --flat
1

# 创建 middleware:

因为这时候并不知道你用的 express 还是 fastify,所以 request、response 是 any,手动标注下类型就好了:

这里是 express 的 request、response。

加一下前后的的逻辑:

import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';

@Injectable()
export class AaaMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: () => void) {
    console.log('brefore');
    next();
    console.log('after');
  }
}
1
2
3
4
5
6
7
8
9
10
11

# 使用

然后在 Module 里这样使用:

import { AaaMiddleware } from './aaa.middleware';
import { MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule implements NestModule{

  configure(consumer: MiddlewareConsumer) {
    consumer.apply(AaaMiddleware).forRoutes('*');
  }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

实现 NestModule 接口的 configure 方法,在里面应用 AaaMiddleware 到所有路由。

然后跑起来试一下:

nest start --watch

浏览器访问 http://localhost:3000 (opens new window)

可以看到中间件的逻辑都执行了:

这里也可以指定更精确的路由。

我们添加几个 handler:

# 指定路由

然后重新指定 Middleware 应用的路由:

import { AaaMiddleware } from './aaa.middleware';
import { MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule implements NestModule{

  configure(consumer: MiddlewareConsumer) {
    consumer.apply(AaaMiddleware).forRoutes({ path: 'hello*', method: RequestMethod.GET });
    consumer.apply(AaaMiddleware).forRoutes({ path: 'world2', method: RequestMethod.GET });
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

可以看到,hello、hello2、world2 的路由都调用了这个中间件,而 world1 没有:

这就是 Nest 里 middleware 的用法。

如果只是这样,那和 Express 的 middleware 差别并不大,无非是变成了 class 的方式。

Nest 为什么要把 Middleware 做成 class 呢?

当然是为了依赖注入了!

我们通过 @Inject 注入 AppService 到 middleware 里:

import { AppService } from './app.service';
import { Inject, Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';

@Injectable()
export class AaaMiddleware implements NestMiddleware {
  @Inject(AppService)
  private readonly appService: AppService;

  use(req: Request, res: Response, next: () => void) {
    console.log('brefore');
    console.log('-------' + this.appService.getHello());
    next();
    console.log('after');
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

当然,这里也可以用构造器注入,这样更简洁一点:

这时在访问这个路由的时候,就可以看到中间件成功调用了 AppService:

这就是 Nest 注入的依赖。

如果不注入依赖,那写函数的方式也是可以的。

看这个 apply 方法的类型声明也可以看出来:

如果不需要注入依赖,那可以写函数形式的 middleware,这时候和 Express 的 middleware 就没啥区别了。

如果需要注入依赖,那就写 class 形式的 middleware,可以用 Nest 的依赖注入能力。

当然,应用实例对象也可以 use 中间件,这个就和 express 那个一样了:

不过这种形式不能注入依赖,而且也不能配置应用到什么路由,不建议用。

app.use 等同于在 AppModule 的 configure 方法里的 forRoutes('*')

此外,middleware 里有个 next 参数,而 Nest 还有个 @Next 装饰器,这俩的区别是什么呢?

middleware 的 next 参数就是调用下一个 middleware 的,这个很好理解。

# @Next

而 @Next 装饰器是调用下一个 handler 的:

但如果是这样一个 handler,它就不返回值了:

这个和加上 @Response 装饰器的时候的效果一样。

因为 Nest 认为你会自己返回响应或者调用下个 handler,就不会处理返回值了。

如果依然想让 Nest 把函数返回值作为响应,可以这样写:

这个上节讲过。

当然,传入 Next 参数的时候,一般是不需要在这里响应的,一般是调用下个 handler 来响应:

不过一般也不需要这样写,直接写在一个 handler 里就行。

有的同学可能会问:Nest 的 middleware 和 interceptor 都是在请求前后加入一些逻辑的,这俩区别是啥呢?

区别有两点:

interceptor 是能从 ExecutionContext 里拿到目标 class 和 handler,进而通过 reflector 拿到它的 metadata 等信息的,这些 middleware 就不可以。

再就是 interceptor 里是可以用 rxjs 的操作符来组织响应处理流程的:

middleware 里也不可以。

它们都是 Nest AOP 思想的实现,但是 interceptor 更适合处理与具体业务相关的逻辑,而 middleware 适合更通用的处理逻辑。

案例代码在小册仓库 (opens new window)。

# 总结

Nest 也有 middleware,但是它不是 Express 的 middleware,虽然都有 request、response、next 参数,但是它可以从 Nest 的 IOC 容器注入依赖,还可以指定作用于哪些路由。

用法是 Module 实现 NestModule 的 configure 方法,调用 apply 和 forRoutes 指定什么中间件作用于什么路由。

app.use 也可以应用中间件,但更建议在 AppModule 里的 configure 方法里指定。

Nest 还有个 @Next 装饰器,这个是用于调用下个 handler 处理的,当用了这个装饰器之后,Nest 就不会把 handler 返回值作为响应了。

middleware 和 interceptor 功能类似,但也有不同,interceptor 可以拿到目标 class、handler 等,也可以调用 rxjs 的 operator 来处理响应,更适合处理具体的业务逻辑。

middleware 更适合处理通用的逻辑。

编辑 (opens new window)
上次更新: 2025/5/14 16:47:16
Nest和Express,fastify
RxJS和Interceptor

← Nest和Express,fastify RxJS和Interceptor→

最近更新
01
IoC 解决了什么痛点问题?
03-10
02
如何调试 Nest 项目
03-10
03
Provider注入对象
03-10
更多文章>
Copyright © 2019-2025 Study | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式