Apollo client query error: “Network error: Failed to fetch” How to troubleshoot?
已安装Apollo服务器,并且在使用graphiql时,它可以正确响应查询。
具有服务器端渲染的现有react-redux应用程序需要开始使用graphql并进行此查询。
此应用程序的一个组件已设置为执行相同的查询,似乎正在执行网络请求,但由于失败而失败
Error: {"graphQLErrors":[],"networkError":{},"message":"Network error: Failed to fetch"}
是否有任何故障排除建议?
这确实是问题。我试图通过使用快递来解决它。但这不适用于Apollo GraphQL。
1 2 3 4 5 | const corsOptions = { origin:"http://localhost:3000", credentials: true }; app.use(cors(corsOptions)); |
因此,我尝试在GraphQL服务器中配置cors并成功运行。
对于Apollo服务器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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}`); }); |
对于GraphQL Yoga
1 2 3 4 5 6 7 | const options = { cors: corsOptions }; server.start(options, () => console.log("Server is running on http://localhost:4000") ); |
我在本地主机上运行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.
此设置(仅测试)的快速解决方案是,如本文所述,在Express Apollo服务器上设置cors。
https://blog.graph.cool/enabling-cors-for-express-graphql-apollo-server-1ef999bfb38d
要做以下工作所需要做的就是为Apollo-Graphql服务器启用cors库
1 | yarn add cors / npm install cors |
现在可以找到app.js或server.js(基本上是服务器的入口文件)
在其中添加以下几行
const cors = require('cors');
app.use(cors()); // Make sure you have express initialised before this.
如果通过Apollo在请求中传递
1 2 3 4 5 | const middlewareLink = setContext(() => ({ headers: { 'authorization': `Bearer ${FeedierExchanger.token}` ||null } })); |
将其更改为:
1 2 3 4 5 | const middlewareLink = setContext(() => ({ headers: { 'authorization': `Bearer ${FeedierExchanger.token}` ||'' } })); |
或删除此部分:
1 | ||'' |
如果您具有正确的后端验证。