Why is the response body empty (0 bytes on network tab) for this request? Is it to do with this being an extension?

心不动则不痛 提交于 2020-03-26 03:58:42

问题


When I use the fetch API (Or xmlhttprequest) I get a 0 byte response. Here is a sample of my code:

    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);});

In the network tab, and in the console.log(res) in the callback, the response is empty. I should note that the response is including a CORS response specifying my chrome extension (which is making the request)

Access-Control-Allow-Origin: chrome-extension://asdjkljuewyrjkhighqwend

When I use the requests library (python) and make the same request (copying and pasting the body of the request) I get a valid json response.

resp = requests.post("https://myurl", json=data)
resp.json() ->> {content}

Additionally, when I inspect the server after the Fetch requests, I can see that it happily responded with the json to the request, but something on the browser seems to be blocking it from getting through.


回答1:


You need to move all XHR requests to the background part of your extension. Chrome no longer accepts content scripts requests.

You can use runtime.sendMessage to send messages to a background process.

chrome.runtime.sendMessage(myMessageObject, async response => {
  // Here is the response returned by the background process
});

And here is how to receive messages from the background perspective.

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {

  return true
})



回答2:


I believe you're indeed looking at a CORS issue. Try including the following headers in the response from your server:

Access-Control-Allow-Origin: * // you already hve this one Access-Control-Allow-Headers: Content-Type Access-Control-Allow-Methods: GET, PUT, POST, OPTIONS



来源:https://stackoverflow.com/questions/55977915/why-is-the-response-body-empty-0-bytes-on-network-tab-for-this-request-is-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!