在NestJS中为所有未定义路由返回405状态码
在NestJS中实现全局405(方法不允许)守卫
1. 创建全局守卫类
实现CanActivate接口,通过Reflector获取路由允许的方法,结合HttpAdapterHost适配不同HTTP框架,设置响应头并抛出405异常:
import { Injectable, CanActivate, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import { HttpAdapterHost } from '@nestjs/core'; @Injectable() export class MethodNotAllowedGuard implements CanActivate { constructor( private reflector: Reflector, private httpAdapterHost: HttpAdapterHost, ) {} canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); // 获取路由标记的允许方法 const allowedMethods = this.reflector.get<string[]>('allowedMethods', context.getHandler()); // 未标记允许方法时默认放行(可根据需求调整为拒绝) if (!allowedMethods) { return true; } const requestMethod = request.method.toUpperCase(); if (!allowedMethods.includes(requestMethod)) { const { httpAdapter } = this.httpAdapterHost; // 设置响应头告知允许的方法 httpAdapter.setHeader(request.res, 'Allow', allowedMethods.join(', ')); throw new HttpException('Method Not Allowed', HttpStatus.METHOD_NOT_ALLOWED); } return true; } }
2. 定义标记允许方法的装饰器
通过SetMetadata创建自定义装饰器,用于在路由上标记允许的HTTP方法:
import { SetMetadata } from '@nestjs/common'; export const AllowedMethods = (...methods: string[]) => SetMetadata('allowedMethods', methods.map(method => method.toUpperCase()));
3. 在控制器路由上使用装饰器
为每个路由指定允许的请求方法:
import { Controller, Get, Post } from '@nestjs/common'; import { AllowedMethods } from './allowed-methods.decorator'; @Controller('demo') export class DemoController { @Get() @AllowedMethods('GET') handleGet() { return '处理GET请求'; } @Post() @AllowedMethods('POST') handlePost() { return '处理POST请求'; } }
4. 注册全局守卫
有两种方式注册全局守卫:
方式一:在main.ts中直接注册
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { MethodNotAllowedGuard } from './method-not-allowed.guard'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalGuards(new MethodNotAllowedGuard()); await app.listen(3000); } bootstrap();
方式二:在模块中通过APP_GUARD注册
import { Module } from '@nestjs/common'; import { APP_GUARD } from '@nestjs/core'; import { MethodNotAllowedGuard } from './method-not-allowed.guard'; @Module({ providers: [ { provide: APP_GUARD, useClass: MethodNotAllowedGuard, }, ], }) export class AppModule {}
这样,当客户端使用路由不允许的方法请求时,会返回405状态码,并在响应头中告知允许的HTTP方法,符合HTTP规范要求。
内容的提问来源于stack exchange,提问作者manaclan
相关产品推荐
相关产品推荐

