Joh*_*ny5 7 apollo reactjs graphql
已设置 Apollo 服务器,并在使用 graphiql 时正确响应查询。
具有服务器端渲染的现有 react-redux 应用程序需要开始使用 graphql 并进行此查询。
此应用程序的一个组件已设置为执行相同的查询,它似乎在执行网络请求,但失败了
Error: {"graphQLErrors":[],"networkError":{},"message":"Network error: Failed to fetch"}
任何故障排除建议?
确实是cors的问题。我尝试使用express 来修复它。但它不适用于 Apollo GraphQL。
const corsOptions = {
origin: "http://localhost:3000",
credentials: true
};
app.use(cors(corsOptions));
Run Code Online (Sandbox Code Playgroud)
因此,我尝试在 GraphQL 服务器内配置 cors,结果成功了。
对于 Apollo 服务器
const corsOptions = {
origin: "http://localhost:3000",
credentials: true
};
const server = new ApolloServer({
typeDefs,
resolvers,
cors: corsOptions
});
server.listen().then(({ url }) => {
console.log(` Server ready at ${url}`);
});
Run Code Online (Sandbox Code Playgroud)
对于 GraphQL Yoga
const options = {
cors: corsOptions
};
server.start(options, () =>
console.log("Server is running on http://localhost:4000")
);
Run Code Online (Sandbox Code Playgroud)
我在 localhost 上运行 apollo 客户端,在 someDomain.com 上运行 apollo 服务器,所以这是一个 CORS 问题。在chrome隐身模式下加载执行查询的页面并刷新后,在chrome开发工具控制台中发现此错误:
httpLink.js:71 OPTIONS https://someDomain.com/graphql 405 (Method Not Allowed)
(anonymous) @ httpLink.js:71
...
(index):1 Failed to load https://someDomain.com/graphql: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:8443' is therefore not allowed access. The response had HTTP status code 405. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Run Code Online (Sandbox Code Playgroud)
对此(仅测试)设置的快速修复是在 Express apollo 服务器上设置 cors,如本文建议的那样。 https://blog.graph.cool/enabling-cors-for-express-graphql-apollo-server-1ef999bfb38d
| 归档时间: |
|
| 查看次数: |
18493 次 |
| 最近记录: |