2
votes

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?

1

1 Answers

7
votes

You're not actually creating a response with JSON. The first argument of Response is a string or a few others, but not a random object. If you want JSON, you need to actually pass JSON, e.g.

var obj = JSON.stringify({ "Prop" : "Some value" });

The error you are getting is because currently it is converted to a string as

"[object Object]"

and

JSON.parse("[object Object]")

throws unexpected token "o".