NestJS学习:中间件

中间件

参考:小满nestjs(第十二章 nestjs 中间件)中间件

与大佬之间的差距是真大,啥时候才能这么牛,还有那些写库的人。人家才是程序员,自己不过是个码农而已。

什么是中间件

中间件是在路由处理程序 之前 调用的函数。 中间件函数可以访问请求和响应对象,从vue开发者的角度来看与路由类似,这里是决定你能不能请求到数据,能够请求到什么数据。

依赖注入中间件

创建中间件

nest g mi logger

执行完后会生成
在这里插入图片描述
大佬是自己手写的,这里我们使用创建好的模板 logger.middleware.ts

  • 导入express中的方法,使我们的中间件可以有相应的提升,修改后如下:
import {
    
     Injectable, NestMiddleware } from '@nestjs/common';

//导入express中的方法
import {
    
     Request, Response, NextFunction } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
    
    
  use(req: Request, res: Response, next: NextFunction) {
    
    
    console.log("根路径", req.baseUrl)
    next();
  }
}
  • 在要使用的模块里注册中间件 customer.module.ts
import {
    
     MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import {
    
     CustomerService } from './customer.service';
import {
    
     CustomerController } from './customer.controller';

//导入中间件
import {
    
     LoggerMiddleware } from '../logger/logger.middleware';

@Module({
    
    
  controllers: [CustomerController],
  providers: [CustomerService],
  //导出客户模块的服务
  exports: [CustomerService],
})
export class CustomerModule implements NestModule {
    
    
  //在模块里面 实现 configure 返回一个消费者  consumer 通过 apply 注册中间件 通过forRoutes 指定  Controller 路由
  configure(consumer: MiddlewareConsumer) {
    
    
    consumer.apply(LoggerMiddleware).forRoutes('customer');
  }
}

访问customer路由会执行拦截器里面的方法
在这里插入图片描述
在这里插入图片描述
除了填写控制器名称外,也可以直接将控制器类当作参数。

 consumer.apply(LoggerMiddleware).forRoutes(CustomerController);

除了上面两种方式外,还支持对象模式,例如针对get请求进行拦截

consumer.apply(LoggerMiddleware).forRoutes({
    
    
  path: 'customer',
  method: RequestMethod.GET,
});

不过不知道什么原因,除了第一种后两种都没能打印出baseUrl

补充
推荐使用第一种方式
特地尝试了一下,也可以针对某一个子路由

customer下新建一个get请求

@Get('/abc')
findAbc() {
    
    
  return '测试子路由';
}

修改中间件的地址

 consumer.apply(LoggerMiddleware).forRoutes('customer/abc');

上述只有在访问customer/abc时才能够生效。

全局中间件

全局中间件只能使用函数模式, 案例可以做白名单拦截之类的

main.ts

import {
    
     NestFactory } from '@nestjs/core';
import {
    
     AppModule } from './app.module';
import {
    
     Request, Response, NextFunction } from 'express';

//白名单
const whiteList = ['/service'];

function middleWareAll(req: Request, res: Response, next: NextFunction) {
    
    
  console.log(req.originalUrl, '我收全局的');

  if (whiteList.includes(req.originalUrl)) {
    
    
    next();
  } else {
    
    
    res.send('小黑子露出鸡脚了吧');
  }
}

async function bootstrap() {
    
    
  const app = await NestFactory.create(AppModule);
  //注册中间件
  app.use(middleWareAll);
  await app.listen(3000);
}
bootstrap();

在这里插入图片描述
在这里插入图片描述

接入第三方中间件 例如 cors 处理跨域

npm install cors
npm install @types/cors -D

好像没有出现跨域的问题,有可能是某些原因吧。但不妨碍我们学习知识点。
在这里插入图片描述

// 在main.ts里引入第三方中间件
import * as cors from 'cors'
//使用中间件
app.use(cors())

猜你喜欢

转载自blog.csdn.net/weixin_41897680/article/details/128891202