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

相关推荐
求知摆渡5 分钟前
共享代码不是共享风险——公共库解耦的三种进化路径
java·后端·架构
brzhang17 分钟前
前端死在了 Python 朋友的嘴里?他用 Python 写了个交互式数据看板,着实秀了我一把,没碰一行 JavaScript
前端·后端·架构
该用户已不存在1 小时前
不知道这些工具,难怪的你的Python开发那么慢丨Python 开发必备的6大工具
前端·后端·python
Xy9101 小时前
开发者视角:App Trace 一键拉起(Deep Linking)技术详解
java·前端·后端
嘻嘻哈哈开森1 小时前
技术分享:深入了解 PlantUML
后端·面试·架构
vvw&1 小时前
Linux 中的 .bashrc 是什么?配置详解
linux·运维·服务器·chrome·后端·ubuntu·centos
厚道1 小时前
Elasticsearch 的存储原理
后端·elasticsearch
不甘打工的程序猿1 小时前
nacos-client模块学习《心跳维持》
后端·架构
方块海绵1 小时前
mysql 中使用 json 类型的字段
后端