Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service Workers: Retrieve xhr body when fetching the request

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

xhr.send("a=1");

On the other side, I have implemented a Service Worker and created the handler to catch all fetch requests

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

I can retrieve some properties of the event.request as event.request.url, but I am unable to find the way to retrieve my original xhr body (i.e. "a=1").

Interestingly, when the Service Worker handles this request, and calls the network to get the result,

return fetch(event.request);

the server get access to the body data.

Below an extract of the Request object I receive within 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 retrieve the content/body of the send request within the Service Worker fetch() capture?

Thanks!

like image 464
Miguel Guardo Avatar asked Sep 22 '16 22:09

Miguel Guardo


1 Answers

This is maybe obvious for most people, but I wanted to add some notes with the response, in case someone is in my same situation in the future.

There are several methods to retrieve the body from the request, depending on how the body has been sent

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

Any of those methods will return a Promise, which will include the body content. Voila!

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

like image 91
Miguel Guardo Avatar answered Nov 12 '22 13:11

Miguel Guardo