服务工作者错误:事件已经被响应

14
我一直收到这个错误信息:
Uncaught (in promise) DOMException: Failed to execute 'respondWith' on 'FetchEvent': The event has already been responded to.
我知道Service Worker在fetch函数中有异步操作时会自动响应,但我无法确定这段代码中哪部分是罪犯。
importScripts('cache-polyfill.js');

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

  var location = self.location;

  console.log("loc", location)

  self.clients.matchAll({includeUncontrolled: true}).then(clients => {
    for (const client of clients) {
      const clientUrl = new URL(client.url);
      console.log("SO", clientUrl);
      if(clientUrl.searchParams.get("url") != undefined && clientUrl.searchParams.get("url") != '') {
        location = client.url;
      }
    }

  console.log("loc2", location)

  var url = new URL(location).searchParams.get('url').toString();

  console.log(event.request.hostname);
  var toRequest = event.request.url;
  console.log("Req:", toRequest);

  var parser2 = new URL(location);
  var parser3 = new URL(url);

  var parser = new URL(toRequest);

  console.log("if",parser.host,parser2.host,parser.host === parser2.host);
  if(parser.host === parser2.host) {
    toRequest = toRequest.replace('https://booligoosh.github.io',parser3.protocol + '//' +  parser3.host);
    console.log("ifdone",toRequest);
  }

  console.log("toRequest:",toRequest);

  event.respondWith(httpGet('https://cors-anywhere.herokuapp.com/' + toRequest));
  });
});

function httpGet(theUrl) {
    /*var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;*/
    return(fetch(theUrl));
}

任何帮助将不胜感激。

2个回答

22

问题在于你调用event.respondWith()的代码在顶级promise的.then()子句中,这意味着它将在顶级promise解析后异步执行。为了获得您期望的行为,event.respondWith()需要作为fetch事件处理程序的执行的一部分同步执行。

你的Promise内部逻辑有点难以跟踪,所以我不确定你想要实现什么,但通常可以遵循以下模式:

self.addEventListerner('fetch', event => {
  // Perform any synchronous checks to see whether you want to respond.
  // E.g., check the value of event.request.url.
  if (event.request.url.includes('something')) {
    const promiseChain = doSomethingAsync()
      .then(() => doSomethingAsyncThatReturnsAURL())
      .then(someUrl => fetch(someUrl));
      // Instead of fetch(), you could have called caches.match(),
      // or anything else that returns a promise for a Response.

    // Synchronously call event.respondWith(), passing in the
    // async promise chain.
    event.respondWith(promiseChain);
  }
});

这就是大概的意思。(如果您最终使用 async/await 替换承诺,代码看起来甚至更加清晰。)


15

当我尝试在fetch处理程序中使用async/await时,我也遇到了这个错误。正如Jeff在他的回答中提到的那样,event.respondWith必须同步调用,而参数可以是任何返回解析为响应的promise的内容。由于async函数确实返回一个promise,所以你所要做的就是将fetch逻辑包装在一个async函数内,在某个时间点返回一个响应对象,并通过该处理程序调用event.respondWith

async function handleRequest(request) {
  const response = await fetch(request)

  // ...perform additional logic

  return response
}

self.addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request));
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接