【问题标题】:Uncaught DOMException (in promise) - Hijack specific GraphQL request in the serviceworkerUncaught DOMException (in promise) - 在 serviceworker 中劫持特定的 GraphQL 请求
【发布时间】:2019-06-09 14:44:47
【问题描述】:

我尝试通过 service-worker 劫持特定的 GraphQL-Request 以伪造来自我的 IndexedDB 中数据的响应,但我收到一个错误,表明该事件已得到响应。提取适用于缓存文件,如果提取的数据不在缓存中,它将使用网络。如果没有网络,将有一个离线回退。我如何编排我的承诺,我还可以劫持对我的 GraphQL API 和特定查询(操作名称)的请求,因为我似乎搞砸了异步 event.respondWith 调用?

self.addEventListener('fetch', function (event) {
    if (event.request.url === __GRAPHQL_URL__) {
        event.request.clone().json().then(({operationName, variables}) => {
            switch (operationName) {
                case 'getOfflineFacilities':
                    //when a fetch is matching there will be the error
                    event.respondWith(serveOfflineFacilities());
            }
        });
    }else{

        event.respondWith(
            caches.match(event.request).then(function (response) {
                console.log("cache or network fallback");
                return response || fetch(event.request);
            }).catch(function () {
                console.log("offline fallback");
                return caches.match('/index.html');
            })
        );
    }
});

当 GraphQL 查询命中 __GRAPHQL_URL__ 和我的 operationName

时出错

sw.js:41 Uncaught (in promise) DOMException: Failed to execute 'respondWith' on 'FetchEvent': The event has already been responded to.

【问题讨论】:

  • 是唯一的fetch 事件监听器吗?
  • 请注意,您永远不会处理 event.request.clone().json() 承诺的失败
  • 是的,只有它一个
  • 我的 switch case 中的 event.respondWith 遥不可及。你知道锄头来解决这个问题,不会早点回复吗?
  • 我上面代码中的那个。我的问题是我的 switch case 中的所有内容都已得到响应

标签: javascript es6-promise service-worker fetch-api


【解决方案1】:

它的文档很少,但您需要在处理程序中调用respondWith method立即。如果事件处理程序退出并且 respondWith 尚未被调用,则请求 will be handled 以便提供默认响应。 respondWith will check the dispatch flag 仅在事件处理程序调用期间设置 - 当您仅从 Promise 回调中调用它时,您将收到“事件已被响应”异常。

因此您需要更改代码以将整个承诺传递给respondWith

if (event.request.url === __GRAPHQL_URL__) {
    event.respondWith(event.request.clone().json().then(({operationName, variables}) => {
//  ^^^^^^^^^^^^^^^^^^
        switch (operationName) {
            case 'getOfflineFacilities':
                return serveOfflineFacilities();
//              ^^^^^^
        }
    }));
//    ^
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-27
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 2021-04-28
    • 1970-01-01
    相关资源
    最近更新 更多