nestjs 全栈进阶--中间件

视频教程

22_nest中中间件_哔哩哔哩_bilibili

1. 介绍

在Nest.js框架中,中间件(Middleware)是一个非常重要的概念,它是HTTP请求和响应生命周期中的一个重要组成部分,允许开发者在请求到达最终的目的控制器方法之前或响应返回客户端之前,对请求或响应进行预处理或后处理。

Nest.js中间件的工作原理是基于洋葱模型(Onion Architecture),也就是请求依次通过一层层的中间件,每个中间件都可以选择是否继续将请求传递给下一个中间件或者提前结束请求。

arduino 复制代码
nest new middleware -p pnpm
sql 复制代码
pnpm start:dev

2. 对所有路由使用

css 复制代码
nest g middleware aaa --no-spec --flat

生成的文件

因为它不知道你用的 express 还是 fastify,所以 request、response 是 any,我们自己修改下

typescript 复制代码
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('开始执行中间件aaa...');
    next();
    console.log('结束执行中间件aaa...');
  }
}

然后在 Module 里这样使用: 实现 NestModule 接口的 configure 方法,在里面应用 AaaMiddleware 到所有路由。

浏览器访问 http://localhost:3000

3. 精确路由使用

先添加几个 handler

kotlin 复制代码
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) { }

  @Get()
  getHello(): string {
    console.log('getHello');
    return this.appService.getHello();
  }

  @Get('hello2')
  getHello2(): string {
    console.log('getHello2');
    return this.appService.getHello();
  }

  @Get('hello3')
  getHello3(): string {
    console.log('getHello3');
    return this.appService.getHello();
  }

  @Get('hello4')
  getHello4(): string {
    console.log('getHello4');
    return this.appService.getHello();
  }

  @Get('hello5')
  getHello5(): string {
    console.log('getHello5');
    return this.appService.getHello();
  }
}

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

当你 访问hello2这个路由时:

4. 注入其他服务到中间件

学习过Express的同学,应该会发现,nest的中间件和Express 的 中间件 差别并不大,无非是变成了 class 的方式,那他为什么要采用class的方式呢?

答案是:为了依赖注入,比如我们可以将AppService 注入到 中间件

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

@Injectable()
export class AaaMiddleware implements NestMiddleware {
  constructor(private readonly appService: AppService) { }

  use(req: Request, res: Response, next: () => void) {
    console.log('开始执行中间件aaa...');
    console.log('----------', this.appService.getHello());
    next();
    console.log('结束执行中间件aaa...');
  }
}

5. nest参数和@Nest装饰器

他的作用就是调用下一个 middleware,

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

当我们再次访问 http://localhost:3000/,你会发现他就卡在这里不动了,这个和加上 @Response 装饰器的时候的效果一样,Nest 认为你会自己返回响应或者调用下个 handler,就不会处理返回值了

此时,我们手动next,

你会发现他404,因为传入 Next 参数的时候,一般是不需要在这里响应的,一般是调用下个 handler 来响应

相关推荐
uzong2 小时前
技术故障复盘模版
后端
GetcharZp2 小时前
基于 Dify + 通义千问的多模态大模型 搭建发票识别 Agent
后端·llm·agent
桦说编程2 小时前
Java 中如何创建不可变类型
java·后端·函数式编程
IT毕设实战小研2 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
wyiyiyi3 小时前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
阿华的代码王国4 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端
Jimmy4 小时前
AI 代理是什么,其有助于我们实现更智能编程
前端·后端·ai编程
AntBlack4 小时前
不当韭菜V1.1 :增强能力 ,辅助构建自己的交易规则
后端·python·pyqt
bobz9655 小时前
pip install 已经不再安全
后端
寻月隐君5 小时前
硬核实战:从零到一,用 Rust 和 Axum 构建高性能聊天服务后端
后端·rust·github