在服务工作者中获取Javascript

时间:2016-07-18 19:23:46

标签: javascript fetch service-worker

我目前正在尝试使用服务工作程序获取事件,使用fetch API向服务器发送请求并返回HTML。我遇到的问题涉及POST请求。当我在POST时尝试执行此操作时,我将丢失POST请求中的所有标头(需要将数据添加到服务器以用于帖子)。我试图手动抓取标题并将它们添加到fetch中,但没有任何运气。这是我当前的fetch事件代码:

self.addEventListener("fetch", function(event) {

    var acceptHeader = event.request.headers.get('Accept');
    //fetch options used for post requests
    var fetchOptionsForPost = {
        method: "post",
        headers: event.request.headers,
        credentials: event.request.credentials
    }


    //if it's a post request, 
    if( acceptHeader.indexOf('text/html') > -1 && event.request.method == "POST" ) {    
        var updatedFetch = fetch( event.request, fetchOptionsForPost).then(function(updatedResponse) {
            //do something with response here.
        });
    }
});

更新

给了crdumoul建议一个镜头并给出以下控制台错误:

ServiceWorker.js:52 Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': Cannot construct a Request with a Request whose mode is 'navigate' and a non-empty RequestInit.
    at TypeError (native)
    at [URL to service worker]

1 个答案:

答案 0 :(得分:0)

尝试在fetchOptionsForPost中将方法更改为“POST”而不是“post”。