Sorry if trivial, or already asked, I can't find any question about that. I dont't know if I'doing right too...
I just beginned learning service workers:
I'd like to return some json object from a service worker for a specific request. N.B.: The code is just testing/learning code: Service Worker Fetching Event:
self.addEventListener('fetch', function(event) {
if(event.request.url.indexOf("not_existing.json") > -1){
var obj = { "Prop" : "Some value" };
event.respondWith(
new Response(obj, {
ok: true,
status: 222,
url: '/'
})
);
}});
Fetch Call:
fetch('not_existing.json')
.then(function(responseObj) {
console.log('status: ', responseObj.status);
return responseObj.json();
})
.then(function (data){
console.log(data);
});
I know that the service worker catches the request, because on "console.log('status: ', responseObj.status);" I get "222", but the script breaks on "return responseObj.json();" with error "Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1"
If I return "plain text" from service worker, and read it with "responseObj.text()" all works great!
On this link "https://developer.mozilla.org/en-US/docs/Web/API/Response/Response" it seems I have only to write the body on Response constructor var myResponse = new Response(body, init);
What's wrong? How to specify the json response object?