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

相关推荐
五敷有你15 分钟前
Go:hello world
开发语言·后端·golang
拔剑纵狂歌34 分钟前
Golang异常处理机制
开发语言·后端·golang·go
缘友一世44 分钟前
Armbian 1panel面板工具箱中FTP服务无法正常启动的解决方法
linux·运维·后端·1panel
weixin_419349791 小时前
flask使用定时任务flask_apscheduler(APScheduler)
后端·python·flask
乐之者v1 小时前
Spring之 IoC、BeanFactory、ApplicationContext
java·后端·spring
一起学习计算机1 小时前
[附源码]基于Flask的演唱会购票系统
后端·python·flask
字节跳动数据平台1 小时前
深耕分析型数据库领域,火山引擎ByteHouse入围《2024爱分析数据库厂商全景报告
数据库·后端·云原生
优秀的颜2 小时前
RabbitMQ(集群相关部署)
开发语言·后端
clisk2 小时前
GO语言入门之准备
开发语言·后端·golang
techlead_krischang2 小时前
合合信息大模型“加速器”重磅上线
后端·go