代码之家  ›  专栏  ›  技术社区  ›  kkesley

JS是否可以让fetch不等待响应?

  •  0
  • kkesley  · 技术社区  · 7 年前

    loggingAPI({
        timestamp: moment()
    })
    window.location = "http://.......com"
    

    日志api只是一个普通的获取包装器。

    但是,服务器现在没有收到API请求。我认为这是因为它甚至没有机会向api发送请求。

    所以我可以等待请求被发送而不是等待响应吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Jaromanda X    7 年前

    使用 sendBeacon 很简单

    没有看到你的代码 loggingAPI 以下是 最佳猜测

    注: sendBeacon 使用POST请求,因此可能需要修改服务器端以接受这样的请求,尽管 正在发送数据,我想它已经在使用 POST -所以这可能不是问题

    window.addEventListener("unload", () => {
        sendBeacon("same url as loggingAPI", JSON.parse({timestamp: moment()}));
    }, false);
    

    那么,当你

    window.location = "http://.......com"
    

    这个 函数被调用

    编辑:对不起,我没有完整的代码,我错过了几步!!

        2
  •  2
  •   Steven Spungin    7 年前

    https://developers.google.com/web/fundamentals/primers/service-workers/

    以下是一些获取特定信息的方法: https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent

    您将注册服务工作者,然后在重定向之前向其发送消息。

    初始复杂性的好处是一旦你开始使用服务人员,他们就打开了一个全新的编程世界;你将最终使用它们,然后排队发送消息。

    步骤1注册服务工作者

    index.html索引

    if ('serviceWorker' in navigator) {
      window.addEventListener('load', function() {
        navigator.serviceWorker.register('service-worker.js').then(function(registration) {
          // Registration was successful
          console.log('ServiceWorker registration successful with scope: ', registration.scope);
        }, function(err) {
          // registration failed :(
          console.log('ServiceWorker registration failed: ', err);
        });
      });
    }
    

    服务工作者.js

    self.addEventListener('install', function(e) {
        return Promise.resolve(null)
    });
    

    步骤3在服务器工作脚本中创建侦听器

    服务工作者.js

    self.addEventListener('message', function (event) {
      console.log('message', event.data)
      // call fetch here, catching and responding to what you stashed in the message      
    });
    

    index.html索引

    只是一个模拟你客户的演示。

     setTimeout(() => {
        navigator.serviceWorker.controller.postMessage({message: 'A LOG MESSAGE'});
      }, 2000)
    

    在你把所有的部分放好之后,确保你关闭所有的标签并重新打开,或者设置chrome开发工具来处理刷新工人。