Apollo Client请求超时失败,但同URL普通Fetch正常问题求助
问题诊断与解决方案
核心问题:IP地址输入错误
看你提供的代码,Apollo Client配置的服务端IP是191.168.11.121,但正常工作的Fetch请求用的是192.168.11.121——这两个地址差了一位数,导致Apollo Client连错了服务器,直接引发连接超时。
修正Apollo Client的uri配置即可解决:
const client = new ApolloClient({ uri: "http://192.168.11.121:3502", // 改成和Fetch一致的正确IP cache: new InMemoryCache(), });
额外排查方向(若IP修正后仍有问题)
如果改完IP还是失败,可以检查以下几点:
- CORS配置:确认Apollo Server是否允许客户端所在局域网IP的跨域请求,虽然Fetch能工作大概率没问题,但可以在服务端配置中明确允许私有网段。
- 显式配置HTTP链接:手动创建
createHttpLink并添加日志,排查Apollo Client内部请求是否有异常:import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client'; const httpLink = createHttpLink({ uri: "http://192.168.11.121:3502", // 打印请求详情用于调试 fetch: (uri, options) => { console.log('Apollo请求详情:', uri, options); return fetch(uri, options); }, }); const client = new ApolloClient({ link: httpLink, cache: new InMemoryCache(), }); - 调整超时时间:Apollo Client默认超时可能偏短,局域网网络波动时可以手动设置更长超时:
const httpLink = createHttpLink({ uri: "http://192.168.11.121:3502", fetchOptions: { signal: AbortSignal.timeout(10000), // 设置10秒超时 }, }); - 服务端监听地址:确认Apollo Server是否绑定
0.0.0.0而非localhost,否则仅能本地访问,局域网其他设备无法连接:// Apollo Server启动示例 const server = new ApolloServer({ typeDefs, resolvers }); await server.listen({ port: 3502, host: '0.0.0.0' });
内容的提问来源于stack exchange,提问作者Ralf Bokelberg
相关产品推荐
相关产品推荐

