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 来响应

相关推荐
GetcharZp1 天前
告别 jq 噩梦!这款 JSON 神器 fx 让你在终端体验“丝滑”的数据操作
后端
小码哥_常1 天前
告别臃肿!Elasticsearch平替Manticore登场
后端
苍何1 天前
万字保姆级教程:Hermes+Kimi K2.6 打造7x24h Agent军团
后端
我叫黑大帅1 天前
为什么map查找时间复杂度是O(1)?
后端·算法·面试
FreeCultureBoy1 天前
用 phpbrew 管理 php 环境:从安装到多版本切换
后端·php
FreeCultureBoy1 天前
用 jenv 管理 Java 环境:从安装 JDK 到多版本切换
后端
IT_陈寒1 天前
Vite的热更新突然失效,原来是因为这个配置
前端·人工智能·后端
考虑考虑1 天前
SQL语句中的order by可能造成时间重复
数据库·后端·mysql
Pkmer1 天前
古法编程: 代理模式
后端·设计模式
文心快码BaiduComate1 天前
Comate搭载Kimi K2.6,长程13h!
前端·后端·程序员