我使用 Apollo Server 和 Apollo Client 创建了一个简单的 graphQL 聊天。
它还使用 session cookie,所以我使用 npm 包 cors
初始化了服务器。像这样:
app.use(
cors({
credentials: true,
origin: "http://localhost:3000"
})
);
在客户端,我使用 apollo 客户端并创建一个像这样的 http 链接:
const httpLink = new HttpLink({
uri: "http://localhost:4000/graphql",
credentials: "include"
});
因此,我包含凭据,并且服务器具有我的客户端的来源(确实是 http://localhost:3000 - create-react-app 默认)。
当我想运行查询时,我在浏览器控制台中收到此错误:
Access to fetch at 'http://localhost:4000/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
为什么它说响应头有一个通配符 * 设置,但在 cors 上我设置了一个特定的来源,所以它不应该是一个通配符对吗?
伙计们,我在这里错过了什么?我当然也重新启动了两台服务器。
当我这样设置客户端时:
const httpLink = new HttpLink({
uri: "http://localhost:4000/graphql",
credentials: "same-origin"
});
我没有从 cors 收到错误消息,但我没有从服务器收到 cookie。 Cookie 有效是因为在 graphQL Playground 上一切都按预期进行。
如果您想查看完整代码:https://github.com/SelfDevTV/graphql-simple-chat
最佳答案
问题已经解决了。
在我的 index.js
来自服务器的文件。
下面几行我将 express 应用程序作为中间件应用到 apollo 服务器实例,如下所示:server.applyMiddleware({ app });
但这会覆盖我上面设置的 cors 选项。
所以我必须这样称呼它:server.applyMiddleware({ app, cors: false });
现在一切正常:)
关于reactjs - 为什么我总是收到不允许通配符 * 的 cors 错误,尽管我在服务器上指定了一个来源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56954070/