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

自定义Hook调用Axios POST接口时product_id为空的问题求助

问题排查:Axios发送form-data POST请求时product_id为空的原因及解决方法

核心问题原因

你直接传递普通JS对象作为请求的data,同时手动设置了Content-Type: multipart/form-data,但Axios不会自动将普通对象转换为FormData实例。这会导致请求体格式不符合后端预期,无法解析出product_id参数;而Postman会自动帮你完成FormData的转换和正确的请求头设置,所以可以正常调用。

解决方案

1. 将请求数据转换为FormData实例

在发送请求前,把要传递的参数手动添加到FormData对象中,确保请求体符合form-data格式要求。

2. 移除手动设置的Content-Type头

当Axios检测到data是FormData类型时,会自动生成包含boundary的正确Content-Type头,手动设置反而会破坏这一机制,导致后端无法正确解析请求体。

修改后的代码示例

自定义Hook部分

const useProductDetails = ({ form }: ListProps) => {
  console.log("form:", form);
  const [response, setResponse] = useState<any>(null);
  const [error, setError] = useState("");

  const fetchData = (data?: any) => {
    console.log("data:", data);
    // 创建FormData并填充参数
    const formData = new FormData();
    const targetData = form ? form : data;
    if (targetData) {
      Object.keys(targetData).forEach(key => {
        formData.append(key, targetData[key]);
      });
    }

    axios({
      method: "POST",
      url: BaseUrl.baseurl + "product_detail",
      data: formData,
      params: { endpoint: "product_detail" },
      headers: {
        accept: "application/json",
        // 移除手动设置的Content-Type,让Axios自动处理
      },
    })
      .then(function (res) {
        if (res) {
          setResponse(res.data);
        }
        console.log("datainside", data);
        console.log("responsedetail", res.data);
      })
      .catch(function (error) {
        console.log("error123", error.response);
        setError(error.response.data.msg);
        console.log("errorcode", error.response.status);
      });
  };

  const callFunc = (data: any) => {
    fetchData(data);
  };

  return { response, error, callFunc };
};

额外检查点

  • 确认product_id参数的键名和后端要求完全一致(注意区分大小写)
  • 检查params中的endpoint: "product_detail"是否符合接口定义要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:55:21