使用Apollo Client调用SWAPI的GraphQL接口出现JSON解析错误求助
问题原因
你遇到的JSON Parse error: Unexpected EOF错误,根源是index.js中配置的fetchOptions: {mode: 'no-cors'}。no-cors是专门用于跨域请求不需要读取返回内容的场景(比如埋点上报),开启后浏览器会拦截响应内容,返回给前端的是空数据,Apollo Client尝试将空内容解析为JSON时就会触发EOF报错。
你直接在GraphQL端点页能正常运行查询,是因为该页面和接口属于同域名,不存在跨域限制,不需要用no-cors模式。
解决步骤
- 首先修改
index.js中的Apollo Client配置,删除useGETForQueries和fetchOptions相关配置:
const client = new ApolloClient({ cache: new InMemoryCache(), link: new HttpLink({ uri: "https://graphql.org/swapi-graphql" }) })
- 如果修改后出现跨域CORS报错,使用本地开发代理解决:
- 若你是通过Create React App创建的项目,直接在项目根目录的
package.json中新增配置项:"proxy": "https://graphql.org" - 再把上面HttpLink的uri改为
"/swapi-graphql" - 重启本地开发服务即可生效
- 修复
App.js中的渲染逻辑,React不支持直接渲染对象类型的data,需要遍历取对应字段渲染,示例代码如下:
else{ return ( <div className="App"> <h1>星球大战API</h1> <div> {data.allPeople.edges.map(edge => { const person = edge.node return <div key={person.id} style={{margin: '16px 0', padding: '8px', borderBottom: '1px solid #eee'}}> <h3>{person.name}</h3> <p>出生年份:{person.birthYear}</p> <p>性别:{person.gender}</p> <p>母星:{person.homeworld?.name}</p> <p>种族:{person.species?.name || '未标注'}</p> </div> })} </div> </div> ); }
内容的提问来源于stack exchange,提问作者Ever Nolasco
相关产品推荐
相关产品推荐

