nestjs 全栈进阶--中间件

视频教程

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

1. 介绍

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

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

nest new middleware -p pnpm
pnpm start:dev

2. 对所有路由使用

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

生成的文件

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

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

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 注入到 中间件

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

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值