为什么此请求的响应正文为空(网络选项卡上为 0 字节)?是不是跟这个扩展有关?
Why is the response body empty (0 bytes on network tab) for this request? Is it to do with this being an extension?
当我使用 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
当我使用请求库 (python) 并发出相同的请求(复制并粘贴请求正文)时,我得到了有效的 json 响应。
resp = requests.post("https://myurl", json=data)
resp.json() ->> {content}
此外,当我在 Fetch 请求后检查服务器时,我可以看到它很高兴地用 json 响应请求,但浏览器上的某些东西似乎阻止它通过。
我相信您确实在查看 CORS 问题。尝试在服务器的响应中包含以下 headers:
Access-Control-Allow-Origin: * // you already hve this one
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, PUT, POST, OPTIONS
您需要将所有 XHR 请求移至扩展程序的后台部分。
Chrome 不再接受内容脚本请求。
您可以使用 runtime.sendMessage 向后台进程发送消息。
chrome.runtime.sendMessage(myMessageObject, async response => {
// Here is the response returned by the background process
});
下面是后台接收消息的方法
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
return true
})
当我使用 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
当我使用请求库 (python) 并发出相同的请求(复制并粘贴请求正文)时,我得到了有效的 json 响应。
resp = requests.post("https://myurl", json=data)
resp.json() ->> {content}
此外,当我在 Fetch 请求后检查服务器时,我可以看到它很高兴地用 json 响应请求,但浏览器上的某些东西似乎阻止它通过。
我相信您确实在查看 CORS 问题。尝试在服务器的响应中包含以下 headers:
Access-Control-Allow-Origin: * // you already hve this one
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, PUT, POST, OPTIONS
您需要将所有 XHR 请求移至扩展程序的后台部分。 Chrome 不再接受内容脚本请求。
您可以使用 runtime.sendMessage 向后台进程发送消息。
chrome.runtime.sendMessage(myMessageObject, async response => {
// Here is the response returned by the background process
});
下面是后台接收消息的方法
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
return true
})