在Google Chrome扩展中,当使用fetch API发送请求时,如果请求的body参数为null,那么fetch函数返回的response对象的body属性也会为null。这是因为在Chrome扩展中,fetch API默认不允许发送包含body的请求,除非在manifest.json文件中的permissions字段中明确声明了需要访问请求body的权限。
要解决这个问题,你可以按照以下步骤进行操作:
示例:
{
"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"]
}
]
}
示例:
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));
示例:
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数据。
领取专属 10元无门槛券
手把手带您无忧上云