注:此文仅记录博主初次学习nestjs之后的认识和理解,经验尚浅,文章内容仅供参考,如若有误,敬请指正。
作为切面
此文暂不对细节展开探讨
1.切面类型:NestMiddleware接口实现类
2.切面输入
- Request对象
- Response对象
- next函数
3.切面输出:next进入下一个切面
4.切面使用场景
- 执行任何代码。
- 对请求和响应对象进行更改。
- 结束请求-响应周期。
- 调用堆栈中的下一个中间件函数。
- 如果当前的中间件函数没有结束请求-响应周期, 它必须调用 next() 将控制传递给下一个中间件函数。否则, 请求将被挂起。
简单案例
1.中间件定义
- 方式1:类中间件
import {
Injectable, NestMiddleware } from '@nestjs/common';
import {
Request, Response } from 'express';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
// 中间件定义:必须是NestMiddleware接口的实现类并且实现use方法,参数为请求、响应、转发到下一个中间件的方法
use(req: Request, res: Response, next: Function) {
console.log('Request...');
next();
}
}
- 方式2:函数式中间件
export function logger(req, res, next) {
console.log(`Request...`);
next();
}
2.中间件注册
- 模块注册(app.module.ts)
import {
Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import {
LoggerMiddleware } from './common/middleware/logger.middleware';
import {
CatsModule } from './cats/cats.module';
import {
CatsController } from './cats/cats.controller.ts';
@Module({
imports: [CatsModule],
})
export class AppModule implements NestModule {
// 中间件注册:不在@module中配置,而是在NestModule接口的configure方法中注册一个中间件消费者(MiddlewareConsumer)实例,在该实例中配置该中间件消费者的消费特征(应用哪个中间件、处理哪些请求、排除哪些请求)。
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)// 可配置多个中间件
.exclude(
{
path: 'cats', method: RequestMethod.GET },
{
path: 'cats', method: RequestMethod.POST },
'cats/(.*)',
)
// forRoutes配置经过中间件的请求有哪些,可接受一个字符串、多个字符串、对象、一个控制器类甚至多个控制器类,传对象时path属性支持通配符*。
.forRoutes(CatsController);
}
}
- 全局注册(main.ts)
const app = await NestFactory.create(AppModule);
app.use(logger);
await app.listen(3000);