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

Angular与NestJS项目CORS问题:预检请求未通过访问控制检查

解决Angular与NestJS间的CORS预检请求失败问题

问题核心:浏览器从http://localhost:4200向http://localhost:3000/card发起请求时,OPTIONS预检请求的响应未返回2xx成功状态码,导致CORS策略拦截请求。

解决步骤:

1. 在NestJS中正确配置CORS

在项目根目录的main.ts里启用并配置CORS,确保包含预检所需的OPTIONS方法:

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

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // 配置CORS规则,适配Angular前端
  app.enableCors({
    origin: 'http://localhost:4200', // 允许的前端源地址
    methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE', 'OPTIONS'], // 必须包含OPTIONS
    allowedHeaders: ['Content-Type', 'Authorization'], // 允许的请求头,按需添加
    credentials: true, // 如果前端带Cookie或认证信息,开启此项
  });
  await app.listen(3000);
}
bootstrap();

2. 避免全局守卫/拦截器拦截OPTIONS请求

如果你的NestJS项目使用了全局守卫、拦截器或异常过滤器,需跳过对OPTIONS预检请求的校验,比如在AuthGuard中添加判断:

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    // 直接放行OPTIONS预检请求
    if (request.method === 'OPTIONS') {
      return true;
    }
    // 你的其他认证逻辑
    return true;
  }
}

3. 验证NestJS服务状态

确保NestJS服务正常运行在3000端口,且没有其他中间件(如日志、路由守卫)修改OPTIONS请求的响应状态码。

Angular端注意事项

Angular侧无需额外配置CORS,直接使用HttpClient发起请求即可:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class CardService {
  constructor(private http: HttpClient) {}

  fetchCardData() {
    return this.http.get('http://localhost:3000/card');
  }
}

内容的提问来源于stack exchange,提问作者sakli ameni

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 19:01:04