2016-09-22 30 views
4

如何检索我从xhr(XMLHttpRequest)发送(正文)调用发送的正文? 我XHR变量是一个XMLHttpRequest准备使用POST方法调用内部URL(例如:/路径/ API)服务人员:提取请求时检索xhr正文

xhr.send("a=1"); 

在另一边,我实现了一个服务人员,并建立了处理程序来捕获所有提取请求

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

我可以检索的event.request作为event.request.url一些属性,但我无法找到找回我原来的身体XHR的方式(即“A = 1”)。

有趣的是,当服务人员处理该请求,并调用网络获得的结果,

return fetch(event.request); 

服务器可以访问的身体数据。

如下申请对象我接收SW内的提取物提取方法

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" 

关于如何服务工人内检索发送请求的内容/体取任何建议()捕获?

谢谢!

回答

4

找到了!

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

有几种方法从请求检索的身体,这取决于如何身体已发送

event.request.arrayBuffer() 
event.request.blob() 
event.request.json() 
event.request.text() 
event.request.formData() 

所有的这些方法会返回一个承诺,其中包括主体内容。瞧!

我还要感谢Nikhil Marathe(https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/)帮助我理解所有这些工作。

干杯!