You need to enable JavaScript to run this app. NestJS如何正确配置限定指定源地址的CORS跨域规则
优惠活动
大模型
产品
解决方案
定价
更多

NestJS如何正确配置限定指定源地址的CORS跨域规则

NestJS 指定域名CORS配置解决方案

配置失效原因

你第一次配置CORS时同时在NestFactory.create初始化参数和app.enableCors()中重复传入了CORS规则,两次配置冲突导致响应头未正常返回。

正确配置方式(二选一即可,不要同时使用)

方式1:初始化时直接配置

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

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    cors: {
      origin: 'http://localhost:8000',
      credentials: true,
    },
  });
  await app.listen(3000);
}
bootstrap();

方式2:单独调用enableCors配置

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

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors({
    origin: 'http://localhost:8000',
    credentials: true,
  });
  await app.listen(3000);
}
bootstrap();

扩展配置说明

  • 多域名允许:如果需要允许多个域名跨域访问,将origin字段改为数组即可:
    origin: ['http://localhost:8000', 'https://www.yourdomain.com']
    
  • 动态域名匹配:如果需要做自定义域名校验,可传入函数实现:
    origin: (origin, callback) => {
      const allowList = ['http://localhost:8000', 'https://www.yourdomain.com'];
      // !origin 兼容同域请求、Postman等不带origin的请求
      if (allowList.includes(origin) || !origin) {
        callback(null, true);
      } else {
        callback(new Error('Not allowed by CORS'));
      }
    }
    

内容的提问来源于stack exchange,提问作者Ruslan Plastun

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 23:12:03