You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NestJS时OPTIONS请求出现404 Not Found错误

解决NestJS中OPTIONS请求返回404的问题

兄弟,我之前踩过一模一样的坑!你遇到的这个情况,本质是浏览器跨域预检的OPTIONS请求没被NestJS正确处理——直接发GET/POST能正常工作,是因为如果是简单请求(比如不带自定义头、Content-Type是application/x-www-form-urlencoded这类),浏览器不会触发预检;但一旦是复杂请求,浏览器会先丢个OPTIONS请求探路,而NestJS默认没配置的话,就会返回404。

给你几个亲测有效的解决办法,按优先级来:

1. 全局配置CORS(最推荐)

直接在main.ts里启用全局CORS配置,NestJS会自动帮你处理所有OPTIONS预检请求,省心又规范:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  
  // 启用CORS并配置必要参数
  app.enableCors({
    origin: 'http://your-frontend-domain.com', // 生产环境指定具体前端域名,开发可以用true允许所有
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS', // 明确包含OPTIONS方法
    allowedHeaders: 'Content-Type, Authorization', // 允许前端带的请求头
    credentials: true, // 如果需要带cookie之类的凭证,打开这个
  });
  
  await app.listen(3000);
}
bootstrap();

配置完重启服务,OPTIONS请求应该就能返回200了。

2. 手动全局拦截OPTIONS请求

如果全局CORS配置因为某些原因不适用(比如有特殊的预检逻辑),可以写一个全局拦截器专门处理OPTIONS:

// src/interceptors/options.interceptor.ts
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class OptionsInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();
    const response = context.switchToHttp().getResponse();
    
    // 捕获OPTIONS请求,直接返回200
    if (request.method === 'OPTIONS') {
      response.status(200).send();
      return new Observable(); // 终止后续路由执行
    }
    
    return next.handle();
  }
}

然后在main.ts里注册这个拦截器:

app.useGlobalInterceptors(new OptionsInterceptor());

3. 针对单个路由处理OPTIONS

如果只是个别路由有问题,也可以在控制器里用@All()装饰器处理所有请求方法,包括OPTIONS:

import { Controller, All, Req, Res } from '@nestjs/common';

@Controller('authenticate')
export class AuthController {
  @All()
  handleAuth(@Req() req, @Res() res) {
    // 处理OPTIONS预检请求
    if (req.method === 'OPTIONS') {
      res.status(200).send();
      return;
    }
    
    // 原来的GET/POST请求逻辑
    if (req.method === 'GET') {
      // ...你的GET处理代码
    } else if (req.method === 'POST') {
      // ...你的POST处理代码
    }
  }
}

不过这种方法比较繁琐,不推荐大规模使用。

总结一下:优先用全局CORS配置,这是NestJS官方推荐的处理跨域和预检请求的方式,大部分场景下都能解决问题。

内容的提问来源于stack exchange,提问作者Francesco Borzi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:01:22