React.js Apollo GraphQL请求失败:状态码400问题排查求助
解决GraphQL Mutation请求400错误的问题
针对你遇到的"Response not successful: Received status code 400"错误,结合你提供的代码,主要有以下几个问题需要修复:
1. Mutation变量与Schema非空约束不匹配
你的后端Schema中,createClientAccount的name参数被定义为必填项(new GraphQLNonNull(GraphQLString)),但前端mutation查询里,$name的类型却设为了非必填的String(缺少!):
// 错误的变量定义 mutation CreateClientAccount($name: String, $email: String!, $password: String!) { createClientAccount(name: $name, email: $email, password: $password) { id auth } }
当你发起请求时,如果name参数为空(比如组件传入的name是undefined),会直接触发Schema的非空校验失败,返回400错误。而你在GraphiQL中测试时应该手动填写了name,所以能成功执行。
修复方案:将mutation中的$name类型改为String!,与Schema保持一致:
mutation CreateClientAccount($name: String!, $email: String!, $password: String!) { createClientAccount(name: $name, email: $email, password: $password) { id auth } }
2. 表单标签语法错误
你的组件中返回的表单标签缺少尖括号,写成了form onSubmit=...,这会导致DOM渲染异常,直接影响表单提交逻辑:
错误代码:
return ( form onSubmit={(e) => { e.preventDefault(); createClientAccount({ variables: { name: name, email: email, password: password } }) }}> </form> )
修复后代码:
return ( <form onSubmit={(e) => { e.preventDefault(); // 可添加日志确认参数是否正确 console.log('提交参数:', { name, email, password }); createClientAccount({ variables: { name, email, password } }) }}> {/* 补充表单输入元素,比如name、email、password的输入框 */} <input type="text" value={name} onChange={/* 绑定更新name的逻辑 */} /> <input type="email" value={email} onChange={/* 绑定更新email的逻辑 */} /> <input type="password" value={password} onChange={/* 绑定更新password的逻辑 */} /> <button type="submit">创建账号</button> </form> )
注意:当前组件没有任何输入控件,需要补充对应的表单元素来收集用户输入,否则传入的name/email/password可能为空值,同样会触发Schema校验失败。
额外排查建议
- 利用Apollo Client的错误对象查看详细报错信息,定位具体问题:
if (error) { console.log('Mutation错误详情:', error.message, error.graphQLErrors); } - 确认组件接收的
name/email/passwordprops是否有有效值,避免传入undefined或空字符串。
内容的提问来源于stack exchange,提问作者mfusco
相关产品推荐
相关产品推荐

