React前端无法触发GraphQL resolver的技术问题求助
解决MERN应用中Apollo客户端mutation触发404错误的问题
核心问题分析
从报错信息Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3000.graphql可以看出两个关键错误:
- 请求端口错误:服务器运行在3001端口,但客户端默认请求了前端的3000端口
- 路径格式错误:地址中缺少斜杠,正确路径应为
http://localhost:3001/graphql
解决方案步骤
1. 修正Apollo客户端的URI配置
找到前端项目中初始化ApolloClient的文件(通常命名为client.js或apollo-client.js),确保uri指向正确的服务器GraphQL端点:
import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client'; import { setContext } from '@apollo/client/link/context'; // 配置正确的服务器GraphQL地址 const httpLink = createHttpLink({ uri: 'http://localhost:3001/graphql', }); // 权限链路等其他配置(如果有) const authLink = setContext((_, { headers }) => { const token = localStorage.getItem('id_token'); return { headers: { ...headers, authorization: token ? `Bearer ${token}` : '', }, }; }); // 创建Apollo客户端实例 const client = new ApolloClient({ link: authLink.concat(httpLink), cache: new InMemoryCache(), }); export default client;
2. 修正mutation返回数据的访问路径
在handleSignupSubmit函数中,你执行的是addUser mutation,但代码中错误地尝试访问data.login.token,需改为data.addUser.token:
const handleSignupSubmit = async (e: React.MouseEvent<HTMLButtonElement>) => { e.preventDefault(); if (!validateForm(signupForm)) return; try { const { data } = await addUser({ variables: { userName: signupForm.username, password: signupForm.pwd, email: signupForm.email, }, }); // 修正为addUser对应的返回字段 auth.login(data.addUser.token); navigate("/"); } catch (err) { console.log(err); } };
3. 验证修复效果
重新启动前端项目,提交注册表单后,检查浏览器网络请求:
- 请求地址应为
http://localhost:3001/graphql - 服务器日志会输出resolver中的打印内容,说明mutation已成功触发
补充说明
Apollo Sandbox能正常工作,是因为它直接使用了服务器启动时输出的http://localhost:3001/graphql地址;而客户端如果未配置正确的uri,会默认请求当前前端域名下的/graphql路径,前端服务器没有该端点,因此返回404错误。
内容的提问来源于stack exchange,提问作者lkalliance
相关产品推荐
相关产品推荐

