You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用Axios调用Hasura GraphQL Mutation接口报错如何解决

问题修复方案

核心报错原因

  • 缺失必要请求头:Axios发送POST请求时未指定Content-Type: application/json,Hasura的GraphQL接口无法识别请求格式,会直接返回400错误。
  • contact字段格式错误:你当前写的{{\"Tel\", 01}, {Email, email@test.com}}存在两处问题:一是Email和邮箱地址未加双引号,语法不合法;二是手动转义双引号会被JS和GraphQL两次解析,最终传到Hasura的格式不符合字段要求。
  • 参数硬编码不符合规范:所有参数直接写在query字符串中,极易出现转义冲突,也不符合GraphQL的最佳实践。

修复后的代码

// 将所有参数抽离为variables,避免手动转义问题
const mutationVariables = {
  fullname: "Company Full Name 344",
  // 按字段要求直接写结构,Axios会自动处理转义
  contact: [
    { Tel: "01" },
    { Email: "email@test.com" }
  ],
  billing_floor_flat_house_no: "floor 14, house 6",
  last_update_by: 112,
  create_by: 112,
  privacy: true,
  propertyData: {
    property_name: "Niketon House",
    building_number: "22C",
    last_update_by: 122,
    create_by: 122,
    app_street: {
      data: {
        street_name: "Long Street",
        district_suburb_county_city: "New City",
        town_city: "New Town",
        country: "Singapore",
        last_update_by: 122,
        create_by: 122
      }
    }
  }
}

Axios.post("http://domain.herokuapp.com/v1/graphql", 
  {
    query: `
      mutation createCompanyBusiness(
        $fullname: String!
        $contact: jsonb!
        $billing_floor_flat_house_no: String!
        $last_update_by: Int!
        $create_by: Int!
        $privacy: Boolean!
        $propertyData: app_property_insert_input!
      ) {
        insert_appcompany(objects: { 
          fullname: $fullname,  
          contact: $contact,  
          billing_floor_flat_house_no: $billing_floor_flat_house_no,  
          last_update_by: $last_update_by,  
          create_by: $create_by, 
          privacy: $privacy,  
          app_property: { 
            data: $propertyData
          } 
        }) { 
          returning { 
            appcompany_id 
          } 
        } 
      }
    `,
    variables: mutationVariables
  },
  {
    headers: {
      "Content-Type": "application/json",
      // 若Hasura配置了访问权限,在此处补充对应的权限头即可
      // "x-hasura-admin-secret": "你的权限密钥",
    }
  }
)
.then((result) => {
  console.log(result);
})
.catch((err) => {
  // 打印Hasura返回的具体错误信息,方便后续排查
  console.log(err.response?.data || err);
});

补充说明

  • 若contact字段不是JSONB类型,而是PostgreSQL数组类型,只需调整variables中contact的结构和query里的变量类型声明即可。
  • 后续遇到同类报错优先打印err.response.data,可以直接看到Hasura返回的具体错误原因(比如字段类型不匹配、权限不足等),排查效率更高。

内容的提问来源于stack exchange,提问作者Kazi Rafi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 04:54:02