首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

为什么我的fetch body在Google Chrome扩展中总是返回null

在Google Chrome扩展中,当使用fetch API发送请求时,如果请求的body参数为null,那么fetch函数返回的response对象的body属性也会为null。这是因为在Chrome扩展中,fetch API默认不允许发送包含body的请求,除非在manifest.json文件中的permissions字段中明确声明了需要访问请求body的权限。

要解决这个问题,你可以按照以下步骤进行操作:

  1. 在你的Chrome扩展的manifest.json文件中,确保已经添加了访问请求body的权限。例如,如果你的扩展需要发送POST请求并包含请求body,你需要在permissions字段中添加"webRequest"和"webRequestBlocking"权限,并在"optional_permissions"字段中添加"http:///"或"https:///",以允许访问所有网站的请求body。

示例:

代码语言:txt
复制
{
  "manifest_version": 2,
  "name": "My Extension",
  "version": "1.0",
  "permissions": [
    "webRequest",
    "webRequestBlocking",
    "http://*/",
    "https://*/"
  ],
  "optional_permissions": [
    "http://*/",
    "https://*/"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_popup": "popup.html",
    "default_icon": "icon.png"
  },
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["content.js"]
    }
  ]
}
  1. 确保你的fetch请求中正确设置了请求的body参数。你可以使用FormData对象来构建请求的body数据,并将其作为fetch函数的第二个参数传递。

示例:

代码语言:txt
复制
const formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

fetch('https://example.com/api', {
  method: 'POST',
  body: formData
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
  1. 如果你仍然遇到问题,可以尝试在fetch请求中添加合适的请求头,例如Content-Type。根据你发送的请求数据类型,选择合适的Content-Type值。

示例:

代码语言:txt
复制
fetch('https://example.com/api', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ key1: 'value1', key2: 'value2' })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

通过以上步骤,你应该能够解决在Google Chrome扩展中fetch body返回null的问题,并成功获取到请求的body数据。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券