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

React调用GraphQL接口报错:变量已传入却提示必填

问题原因与解决方案

核心问题是你的GraphQL POST请求没有携带变量数据:虽然你在查询字符串里定义了$kindd变量,但在请求体里只传了query字段,服务器无法获取到kindd的实际值,因此抛出“Variable ... is required”错误。

修正后的React请求代码

useEffect(() => {
  const kindd = [1, 2];
  const typeosQuery_param = `query ($kindd:[Int!]!){
        typeos(kindd: $kindd,flag:1){
            kindd
            name
            basis
        }
    }
  `;

  fetch("https://localhost:0094/graphql/", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      query: typeosQuery_param,
      variables: { kindd } // 新增变量传递字段
    })
  })
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));
}, []);

关键说明

  • GraphQL POST请求使用变量时,请求体必须包含两个核心字段:
    • query:定义好的GraphQL查询字符串
    • variables:存储所有查询变量实际值的对象,键名要和查询中定义的变量名完全匹配
  • 你在GraphQL playground测试正常,是因为playground会自动帮你绑定变量与查询并传递给服务器;手动编写fetch请求时,需要自行完成变量的传递逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:30:51