Graphql 突变返回 Post 400 错误,不知道如何解决
Posted
技术标签:
【中文标题】Graphql 突变返回 Post 400 错误,不知道如何解决【英文标题】:Graphql mutation returning a Post 400 Error, not sure how to resolve 【发布时间】:2020-11-02 02:45:34 【问题描述】:我尝试在 React 中使用输入表单来执行 graphql 突变并将团队添加到数据库中,这将导致我的 React 前端出现团队卡。我可以使用 GraphQL 游乐场手动执行突变,但不确定如何使用输入表单来执行相同的操作。我已经从函数转移到了类,然后又回到了函数组件,只是无法做到这一点..
解析器中的 Mutation.js 文件
createTeam(parent, args, prisma , info)
return prisma.mutation.createTeam(
data:
title: args.data.title,
agegroup: args.data.agegroup,
published: args.data.published,
coachcreator:
connect:
id: userId
, info)
,
Schema.graphql 文件
type Mutation
createTeam(data: CreateTeamInput!): Team!
input CreateTeamInput
title: String!
agegroup: String!
published: Boolean!
type Team
id: ID!
title: String!
agegroup: String!
published: Boolean!
coachcreator: User!
players: [Player!]!
updatedAt: String!
createdAt: String!
Form.jsx 文件
const ADD_TEAM = gql`
mutation AddTeam($title: String!, $agegroup: String!, $published: String!, $coachcreator: String!)
createTeam(title: $title, agegroup: $agegroup, published: $published, coachcreator: $coachcreators,
)
id
title
agegroup
coachcreator
name
`
function AddTeamForm()
const [title, setTitle] = useState('')
const [agegroup, setAgeGroup] = useState('')
const [coachcreator, setCoachCreator] = useState('')
const [createTeam, error ] = useMutation(ADD_TEAM,
variables: title, agegroup, coachcreator , refetchQueries: ["GET_TEAMS"]
)
if (error)
console.log('error: ', error)
return (
<div className="AddForm">
<MDBRow>
<MDBCol md="3">
<MDBInput label="Title:" name="title" type="text" onChange=e => setTitle(e.target.value)>
</MDBInput>
</MDBCol>
<MDBCol md="3">
<MDBInput label="Age Group:" name="agegroup" type="text" onChange=e => setAgeGroup(e.target.value)>
</MDBInput>
</MDBCol>
<MDBCol md="3">
<MDBInput label="CoachCreator" name="coachcreator" type="text" onChange=e => setCoachCreator(e.target.value)>
</MDBInput>
</MDBCol>
</MDBRow>
<MDBBtn color="success" type="submit" onClick=createTeam>
Submit Form
</MDBBtn>
</div>
);
export default AddTeamForm
我收到 400 错误请求错误,但无法确定问题所在。我还研究了 Graphql 和 Apollo Docs 几个小时,但仍然不确定解决方案。
有任何想法或推动正确方向吗?谢谢。
【问题讨论】:
【参考方案1】:您的架构“声称”createTeam
突变需要 data
参数(CreateTeamInput 形):
类型突变 createTeam(数据:CreateTeamInput!):团队!
在 graphiql 查询变量可能看起来像:
data:
title: "some title",
agegroup: "some group",
published: "some date"
...而且您不能“重新定义”(在客户端)突变(后端)要求,因此定义突变“同步”与 API 形状:
const ADD_TEAM = gql`
mutation AddTeam($data: CreateTeamInput!)
createTeam(data: $data)
id
title
agegroup
coachcreator
name
`
...并将data
对象作为变量传递,而不是单独的值:
function AddTeamForm()
const [title, setTitle] = useState('')
const [agegroup, setAgeGroup] = useState('')
const [coachcreator, setCoachCreator] = useState('')
const [createTeam, error ] = useMutation(ADD_TEAM,
variables:
data:
title,
agegroup,
published: "some date"
, refetchQueries: ["GET_TEAMS"]
)
【讨论】:
完美!非常感谢您的帮助。这是我不确定的数据的对象和使用。真的很感激以上是关于Graphql 突变返回 Post 400 错误,不知道如何解决的主要内容,如果未能解决你的问题,请参考以下文章
在 React Js 中的突变请求时在 GraphQL 中获得 400