从服务工作者返回的javascript中的响应对象中的json内容

Fal*_*lco 2 javascript json fetch ecmascript-6 service-worker

对不起,如果是微不足道的,或者已经被问过,我找不到任何关于此的问题.我不知道我是否也是对的......

我刚刚开始学习服务工作者:

我想从服务工作者返回一些json对象以获取特定请求.注意:代码只是测试/学习代码:服务工作者获取事件:

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: '/'
        })
    );    
}});
Run Code Online (Sandbox Code Playgroud)

取电话:

fetch('not_existing.json')
.then(function(responseObj) {
    console.log('status: ', responseObj.status);
    return responseObj.json();
})
.then(function (data){
    console.log(data); 
});
Run Code Online (Sandbox Code Playgroud)

我知道服务工作者捕获请求,因为在"console.log('status:',responseObj.status);" 我得到"222",但脚本中断"return responseObj.json();" 错误"Uncaught(in promise)SyntaxError:位于1的JSON中的意外标记o"

如果我从服务工作者返回"纯文本",并用"responseObj.text()"读取它,一切都很好!

在这个链接" https://developer.mozilla.org/en-US/docs/Web/API/Response/Response "看起来我只需要在Response构造函数上编写正文var myResponse = new Response(body, init);

怎么了?如何指定json响应对象?

log*_*yth 6

您实际上并没有使用JSON创建响应.第一个参数Response是字符串或其他几个,但不是随机对象.如果你想要JSON,你需要实际传递JSON,例如

var obj = JSON.stringify({ "Prop" : "Some value" });
Run Code Online (Sandbox Code Playgroud)

您得到的错误是因为当前它被转换为字符串

"[object Object]"
Run Code Online (Sandbox Code Playgroud)

JSON.parse("[object Object]")
Run Code Online (Sandbox Code Playgroud)

抛出unexpected token "o".