React调用GraphQL Mutation传parentId时出现400错误求助
问题:React调用GraphQL Mutation添加parentId后返回400 Bad Request
仅传入id参数时接口正常工作,添加parentId参数后就返回400错误,请求排查原因。
ApolloGraphQL 服务端代码
schema.gql
type Mutation { updatePackaging(id: String!, parentId: String): Packaging! }
ProjectResolver.ts
@Mutation(() => Packaging) async updatePackaging( @Arg("id") id: string, @Arg("parentId", { nullable: true }) parentId: string, @Ctx() context: Context ) { console.log(`씨발!!! ${id}, ${parentId}`); return { id, parentId, }; }
React + TypeScript 客户端代码
可正常运行的版本
export const fetchUpdatePackaging = (packaging: types.Packaging) => http.post<{ updatePackaging: types.Packaging | null }>("/", { query: ` mutation UpdatePackaging($id: String!) { updatePackaging(id: $id) { id } } `, variables: { id: packaging.id, }, });
出现400错误的版本(仅添加parentId参数)
export const fetchUpdatePackaging = (packaging: types.Packaging) => http.post<{ updatePackaging: types.Packaging | null }>("/", { query: ` mutation UpdatePackaging($id: String!, $parentId: String) { updatePackaging(id: $id, parentId: $parentId) { id parentId } } `, variables: { id: packaging.id, parentId: packaging.parentId, }, });
排查方向
查看请求详情:打开浏览器控制台的Network标签,找到对应的GraphQL请求,查看
Request Payload里的variables字段,确认parentId的实际值;再看Response里的错误信息,GraphQL通常会返回具体的错误原因(比如变量类型不匹配、值无效等),这是最直接的排查依据。检查parentId的值类型:如果
packaging.parentId是undefined,多数HTTP库会自动省略这个字段,导致请求的variables里没有parentId,但客户端mutation声明了该变量,可能引发格式错误。此时可以把undefined转为null后再传:variables: { id: packaging.id, parentId: packaging.parentId ?? null, }修正服务端Resolver类型:服务端Resolver里
parentId的TypeScript类型是string,但@Arg标记了nullable: true,说明该参数可以为null,因此类型应该改成string | null,否则传null时会触发TypeScript类型错误,导致服务端返回400:@Arg("parentId", { nullable: true }) parentId: string | null,确认客户端变量类型声明:虽然GraphQL中
String类型默认允许null,但如果需要明确标记可选,可以在客户端mutation里把变量写成$parentId: String(和服务端保持一致),避免歧义。
内容的提问来源于stack exchange,提问作者Ian Cho
相关产品推荐
相关产品推荐

