为什么我总是收到不允许通配符 * 的 cors 错误,尽管我在服务器上指定了一个来源?

Ger*_*cke 5 cors express reactjs graphql

我使用 Apollo Server 和 Apollo Client 创建了一个简单的 graphQL 聊天。

它还使用会话 cookie,所以我使用 npm 包初始化服务器,cors如下所示:

app.use(
  cors({
    credentials: true,
    origin: "http://localhost:3000"
  })
);
Run Code Online (Sandbox Code Playgroud)

在客户端,我使用 apollo 客户端并创建一个像这样的 http 链接:

const httpLink = new HttpLink({
  uri: "http://localhost:4000/graphql",
  credentials: "include"
});
Run Code Online (Sandbox Code Playgroud)

因此,我包含凭据,并且服务器具有我的客户端的来源(确实是http://localhost:3000 - create-react-app 默认值)。

当我想运行查询时,我在浏览器控制台中收到此错误:

从源“ http://localhost:3000 ”获取“ http://localhost:4000/graphql ”的访问已被 CORS 策略阻止:响应中“Access-Control-Allow-Origin”标头的值当请求的凭据模式为“包含”时,不得为通配符“*”。

为什么它说响应头有一个通配符 * 集,但在 cors 上我设置了一个特定的来源,所以它不应该是一个通配符对吗?

伙计们,我在这里错过了什么?我当然也重新启动了两台服务器。

当我这样设置客户端时:

const httpLink = new HttpLink({
  uri: "http://localhost:4000/graphql",
  credentials: "same-origin"
});
Run Code Online (Sandbox Code Playgroud)

我没有从 cors 收到错误消息,但我没有从服务器收到 cookie。Cookie 有效是因为在 graphQL Playground 上一切都按预期进行。

如果你想看完整代码:https : //github.com/SelfDevTV/graphql-simple-chat

Ger*_*cke 11

问题已经解决了。

在我index.js来自服务器的文件中。下面几行我将 express 应用程序作为中间件应用到 apollo 服务器实例,如下所示:

server.applyMiddleware({ app });

但这会覆盖我上面设置的 cors 选项。

所以我必须这样称呼它: server.applyMiddleware({ app, cors: false });

现在一切正常:)


小智 8

您可以改为告诉 Apollo 服务器如何配置 cors。

const corsOptions = {
  origin: "http://localhost:3000",
  credentials: true
}

server.applyMiddleware({
  app,
  cors: corsOptions
}) 
Run Code Online (Sandbox Code Playgroud)

然后你可以完全消除 express cors 中间件。

  • 这对我有用。我认为这应该是公认的答案。 (2认同)