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

Node.js中Apollo Server配置CORS时提示Access-Control-Allow-Origin不能为通配符*

问题原因
  • 报错的核心原因是 Apollo Server 内置了独立的 CORS 配置,优先级高于你在 Express 全局注册的 cors 中间件,全局配置的 CORS 规则会被 Apollo Server 针对 GraphQL 接口的默认规则覆盖。
  • 未专门配置 Apollo 侧的 CORS 时,Apollo 默认会返回通配符 * 作为 Access-Control-Allow-Origin 响应头,和你设置的 credentials: true 产生冲突,因此触发报错。
  • 你修改 origin 为 Google 地址测试生效的原因是:测试时请求的是普通 Express 接口,没有命中 Apollo 监听的 /graphql 端点,不会触发 Apollo 的 CORS 覆盖逻辑。
解决方案

你可以选择以下任意一种方式修复:

方案1:直接在 Apollo Server 配置中定义 CORS 规则

在调用 applyMiddleware 挂载 Apollo 服务时,把 CORS 配置写到参数中:

const app = express();
const server = new ApolloServer({
  // 你的 typeDefs、resolvers 等服务配置
});

await server.start();
server.applyMiddleware({
  app,
  // 直接在这里配置CORS,覆盖默认规则
  cors: {
    credentials: true,
    origin: 'https://studio.apollographql.com'
  }
});

方案2:关闭 Apollo 内置 CORS,使用全局 Express 中间件

如果你希望统一使用 Express 全局注册的 cors 中间件,可以关闭 Apollo 自身的 CORS 能力:

const app = express();
// 先注册全局cors中间件
app.use(cors({
  credentials:true,
  origin: 'https://studio.apollographql.com'
}));

const server = new ApolloServer({
  // 你的服务配置
});
await server.start();
server.applyMiddleware({
  app,
  // 关闭Apollo内置CORS,使用全局配置
  cors: false
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 15:18:03