在NestJS中,中间件(Middleware)和守卫(Guard)是两种不同的机制,用于在请求处理的不同阶段执行逻辑。下面是如何在这两者中编写逻辑的详细解释。
基础概念:
中间件是在路由处理器之前执行的函数。它可以访问请求对象(req
)、响应对象(res
)以及下一个中间件函数(next
)。中间件通常用于执行如日志记录、请求体解析、错误处理等横切关注点。
优势:
类型:
应用场景:
示例代码:
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
console.log(`Request...`, req.method, req.url);
next();
}
}
在模块中应用中间件:
import { Module, MiddlewareConsumer } from '@nestjs/common';
import { AppController } from './app.controller';
import { LoggerMiddleware } from './logger.middleware';
@Module({
imports: [],
controllers: [AppController],
})
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(LoggerMiddleware).forRoutes('*');
}
}
基础概念: 守卫是一种特殊的装饰器,用于保护路由。守卫可以在方法执行前进行检查,并决定是否允许请求继续。守卫可以访问请求对象和响应对象,但它们不能修改它们。
优势:
类型:
应用场景:
示例代码:
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
return this.validateRequest(request);
}
private validateRequest(req: any): boolean {
// 在这里编写你的验证逻辑
return req.headers.authorization === 'Bearer valid_token';
}
}
在控制器或方法上应用守卫:
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from './auth.guard';
@Controller('protected')
export class ProtectedController {
@Get()
@UseGuards(AuthGuard)
getProtectedResource() {
return 'This is a protected resource';
}
}
问题:守卫中的逻辑执行后,如何处理不同的结果? 解决方法:
true
,请求将继续。false
或抛出异常,NestJS将自动返回401 Unauthorized响应。问题:如何在中间件中处理错误? 解决方法:
try-catch
块捕获异常。next(error)
将错误传递给下一个中间件或错误处理中间件。通过上述方法,你可以在NestJS中有效地使用中间件和守卫来处理各种逻辑需求。
领取专属 10元无门槛券
手把手带您无忧上云