服务工作者:在获取请求时检索xhr正文

Mig*_*rdo 6 xmlhttprequest send fetch service-worker

如何检索我从xhr(XMLHttpRequest)发送(正文)调用发送的主体?我的xhr变量是一个XMLHttpRequest,可以使用POST方法调用内部URL(例如:/ path/api)

xhr.send("a=1");
Run Code Online (Sandbox Code Playgroud)

另一方面,我实现了一个Service Worker并创建了处理程序以捕获所有获取请求

self.addEventListener('fetch', function(event, body) 
{ 
event.respondWith( //Check content of event.request.body to run the right action );
}
Run Code Online (Sandbox Code Playgroud)

我可以将event.request的一些属性检索为event.request.url,但我无法找到检索原始xhr体的方法(即"a = 1").

有趣的是,当服务工作者处理此请求,并调用网络获取结果时,

return fetch(event.request);
Run Code Online (Sandbox Code Playgroud)

服务器可以访问正文数据.

下面是我在SW fetch方法中收到的Request对象的摘录

Request {method: "POST", url: "http://localhost/services", headers: Headers
, referrer: "http://localhost/m1/", referrerPolicy: "no-referrer-when-downgrade"…}

bodyUsed:false
credentials:"include"
headers:Headers
  __proto__:Headers
integrity:""
method:"POST"
mode:"cors"
redirect:"follow"
referrer:"http://localhost/path/"
referrerPolicy:"no-referrer-when-downgrade"
url:"http://localhost/path/api"
Run Code Online (Sandbox Code Playgroud)

有关如何在Service Worker fetch()捕获中检索发送请求的内容/主体的任何建议?

谢谢!

Mig*_*rdo 9

找到了!

对于大多数人来说这可能是显而易见的,但是我想在回复中添加一些注释,以防将来有人处于同样的情况.

有几种方法可以从请求中检索正文,具体取决于正文的发送方式

event.request.arrayBuffer()
event.request.blob()
event.request.json()
event.request.text()
event.request.formData()
Run Code Online (Sandbox Code Playgroud)

任何这些方法都将返回Promise,其中包括正文内容.瞧!

我还要感谢Nikhil Marathe(https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/)帮助我了解这一切是如何运作的.

干杯!