当我使用 fetch API(或 xmlhttprequest)时,我得到 0 字节响应。这是我的代码示例:
fetch("https://myurl", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({content: content})
}).then(function(res){ return res.text()}).then(function(res){ return cb(res);});
在网络选项卡和回调中的 console.log(res) 中,响应为空。我应该注意到,响应包含一个 CORS 响应,指定我的 chrome 扩展(正在发出请求)
Access-Control-Allow-Origin: chrome-extension://asdjkljuewyrjkhighqwend
当我使用 requests 库 (python) 并发出相同的请求(复制并粘贴请求正文)时,我得到了有效的 json 响应。
resp = requests.post("https://myurl", json=data)
resp.json() ->> {content}
此外,当我在 Fetch 请求之后检查服务器时,我可以看到它很高兴地用 json 响应了请求,但浏览器上的某些东西似乎阻止了它的通过。
最佳答案
您需要将所有 XHR 请求移至扩展程序的后台部分。 Chrome 不再接受内容脚本请求。
您可以使用runtime.sendMessage将消息发送到后台进程。
chrome.runtime.sendMessage(myMessageObject, async response => {
// Here is the response returned by the background process
});
下面是如何从后台 Angular 接收消息。
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
return true
})
关于javascript - 为什么此请求的响应正文为空(网络选项卡上为 0 字节)?这与扩展有关吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55977915/