Workers: extracting xhr body upon receipt of request

How can I get the body sent from the send (body) xhr (XMLHttpRequest) call ?. My xhr variable is an XMLHttpRequest ready to invoke an internal URL using the POST method (Ex: / path / api)

xhr.send("a=1"); 

On the other hand, I implemented Service Worker and created a handler to catch all the select requests

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

I can get some event.request properties as event.request.url, but I cannot find a way to get the original xhr body (ie "a = 1").

I wonder when Service Worker processes this request and calls the network to get the result,

 return fetch(event.request); 

the server accesses the body data.

Below is the extract of the Request object that I get as part of the SW fetch method

 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" 

Any suggestion on how to get the contents / body of a send request as a result of capture () capture of a Worker service?

Thanks!

+5
source share
1 answer

Found!

This may seem obvious to most people, but I wanted to add some notes with the answer if someone is in my situation in the future.

There are several ways to retrieve a body from a request, depending on how the body is sent.

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

Any of these methods will return a promise that will contain the contents of the body. Voila!

I also need to thank Nikhil Marathe ( https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/ ) for helping me understand how this all works.

Hooray!

+4
source

All Articles