我目前正在尝试使用服务工作者fetch事件,使用fetch API向服务器发送请求并获取HTML。我遇到的问题涉及POST请求。当我在POST时尝试这样做时,我会丢失POST请求中的所有标头(需要将数据添加到服务器中以用于发布)。我正试图手动获取标题并将其添加到提取中,但没有任何运气。这是我当前获取事件的代码:
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]
尝试在fetchOptionsForPost中将方法更改为"POST",而不是"POST"。