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

Firefox中手动创建的Request对象缺失body问题求助

Firefox v118.0.2中手动创建Request对象无法访问body属性的问题及解决办法

问题现象

手动实例化Request对象后,在Firefox v118.0.2中无法访问其body属性,触发"request.body is missing"报错。相同代码在Chrome、Edge、Safari中可正常执行,弹出成功提示。测试代码如下:

(() => {
  const request = new Request("/api/login", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ name: "John Wick", password: "P@ssw0rd!" }),
  });
  if (!request.body) {
    return alert("Error: request.body is missing");
  }
  alert(`Success! request has body!`);
})();

但直接使用fetch发送相同配置的请求时,Firefox网络面板能正常显示请求体内容。

原因

根据MDN兼容性说明,Firefox目前未实现Request.body属性的直接访问,而其他主流浏览器已支持该特性。

解决办法

方案1:克隆Request对象并读取内容

由于body是可读流,读取后会被消耗,需先克隆请求对象再读取内容:

(() => {
  const request = new Request("/api/login", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ name: "John Wick", password: "P@ssw0rd!" }),
  });
  request.clone().text().then(bodyContent => {
    if (!bodyContent) {
      alert("Error: request body is empty");
    } else {
      alert(`Success! Request body: ${bodyContent}`);
    }
  });
})();

方案2:提前保存请求体内容

创建Request对象前先将body内容存入变量,后续直接验证该变量:

(() => {
  const bodyContent = JSON.stringify({ name: "John Wick", password: "P@ssw0rd!" });
  const request = new Request("/api/login", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: bodyContent,
  });
  if (!bodyContent) {
    return alert("Error: request body is missing");
  }
  alert(`Success! request has body!`);
})();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:08:27