Apollo Client调用API持续返回404错误,请求排查解决
解决Apollo Client请求404错误的方案
核心问题定位
你的Apollo Client配置里的uri参数存在语法错误:
uri: "'https://countries.trevorblades.com/",
这里多了一个开头的单引号,且URL末尾未闭合引号,导致实际请求的是带无效前缀的错误地址,服务器返回404。
修正步骤
- 修复uri参数
将uri改为正确格式,移除多余单引号并补全闭合:
const client = new ApolloClient({ uri: "https://countries.trevorblades.com/", cache: new InMemoryCache(), });
- 清理冗余代码
App.js中导入了Users组件但未使用,可删除该导入语句:
// App.js // 移除该行:import Users from "./components/Users"; function App() { return ( <div className="container"> <Countries /> </div> ); } export default App;
- 验证查询逻辑
GET_COUNTRIES查询语句是正确的,修正uri后即可正常获取数据。若仍有问题,可通过浏览器开发者工具的Network标签,检查请求地址是否正确,确认请求是否发送到目标API。
修正后的完整index.js示例
//index.js import React from 'react'; import ReactDOM from 'react-dom/client'; import { ApolloProvider, ApolloClient, InMemoryCache } from "@apollo/client"; import App from './App'; const client = new ApolloClient({ uri: "https://countries.trevorblades.com/", cache: new InMemoryCache(), }); const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <React.StrictMode> <ApolloProvider client={client}> <App /> </ApolloProvider> </React.StrictMode> );
内容的提问来源于stack exchange,提问作者cordovez
相关产品推荐
相关产品推荐

