React Apollo客户端调用创建用户GraphQL Mutation时Express返回500错误
问题修复方案
核心问题汇总
- 前端Mutation语法错误:变量定义之间缺少逗号,不符合GraphQL语法规范
- 服务端addCustomer Mutation返回值类型不匹配:定义返回单个CustomerType对象,实际返回了customers数组,触发类型校验错误
- 字段类型不统一:CustomerType中id定义为String类型,addCustomer的入参id定义为Int类型,类型冲突
- 前端入参类型错误:age从输入框获取为字符串类型,与Mutation要求的Int类型不匹配
- 前端错误捕获位置错误:addCustomer是异步方法,调用后立即判断error无法拿到异步返回的错误信息
- 补充说明:express-graphql默认同时支持GET和POST请求,不需要额外配置POST路由,Query和Mutation会自动识别处理
修复步骤
1. 修复前端Mutation语法
import {gql} from '@apollo/client'; export const CREATE_CUSTOMER_MUTATION = gql` mutation addCustomer($id: Int!, $name: String!, $email: String!, $age: Int!){ addCustomer(id: $id, name: $name, email: $email, age: $age) { id name email age } } `
2. 修复前端表单代码
转换age、id为数字,调整错误捕获逻辑:
import React, {useState, useEffect} from 'react' import { CREATE_CUSTOMER_MUTATION } from '../GraphQL/Mutations' import { useMutation } from '@apollo/client'; export default function Form() { const [id,setId] = useState(""); const [name,setName] = useState(""); const [email,setEmail] = useState(""); const [age,setAge] = useState(""); const [addCustomer, {error}] = useMutation(CREATE_CUSTOMER_MUTATION, { onError: (err) => console.log(err) }) const newCustomer = () =>{ addCustomer({ variables: { id: parseInt(id), name: name, email: email, age: parseInt(age) } }) }; // 监听error变化输出错误 useEffect(() => { if(error) console.log(error) }, [error]) return ( <div> <input type="text" placeholder="id" onChange = {(e) =>{ setId(e.target.value)}}/> <input type="text" placeholder="name" onChange = {(e) =>{ setName(e.target.value)}}/> <input type="text" placeholder="email" onChange = {(e) =>{ setEmail(e.target.value)}}/> <input type="text" placeholder="age" onChange = {(e) =>{ setAge(e.target.value)}}/> <button onClick={newCustomer}>Create Customer</button> </div> ) }
3. 修复服务端Schema代码
统一id类型,修正addCustomer的resolve逻辑:
// 先统一CustomerType的id为Int类型,和addCustomer入参匹配 const CustomerType = new GraphQLObjectType({ name: 'Customer', fields: () =>({ id: {type:GraphQLInt}, name: {type:GraphQLString}, email: {type:GraphQLString}, age: {type: GraphQLInt} }) }) // 修正addCustomer的resolve函数 const mutation = new GraphQLObjectType({ name: 'mutation', fields:{ addCustomer:{ type:CustomerType, args:{ id: {type: new GraphQLNonNull(GraphQLInt)}, name: {type: new GraphQLNonNull(GraphQLString)}, email: {type: new GraphQLNonNull(GraphQLString)}, age: {type: new GraphQLNonNull(GraphQLInt)} }, resolve(parentValue,args){ // 构造新的客户对象,加入数组后返回该对象 const newCustomer = {...args} customers.push(newCustomer) return newCustomer } }, // 其余原有代码保持不变即可 } })
内容的提问来源于stack exchange,提问作者luther wardle
相关产品推荐
相关产品推荐

