需要在navigator.sendbeacon()中进行授权 [英] Need authorization in a navigator.sendbeacon()

查看:438
本文介绍了需要在navigator.sendbeacon()中进行授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,当我调用一个侦听onBeforeUnload()事件的函数时,我想发布数据.问题是我的请求未经授权.我需要将承载添加到某个地方,但是我不知道如何.

My problem is that when i call a function who listen to the event onBeforeUnload(), i want to post a data. The problem is that my request is unauthorized. I need to add my bearer somewhere, but i don't know how.

这是我的实际代码:

@HostListener('window:beforeunload', ['$event'])
  onBeforeUnload(): void {
     navigator.sendbeacon(`${localhost:8080/apiRest}`, infoIWantToSent);
  }

目前,该请求发送的是401:unhautorized,这很正常,因为我没有传输任何承载.

For now, the request send a 401:unhautorized, which is normal, since i don't transmit any bearer.

推荐答案

我找到了这个解决方案:

I find this solution :

@HostListener('window:beforeunload', ['$event'])
  onBeforeUnload(): void {
   fetch('url', {
        keepalive: true,
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify(infoIWantToSent),
      });
}

显然,如果必须使用令牌连接,则不能使用navigator.sendbeacon()

Aparently, if we must use a token connexion, we can't use navigator.sendbeacon() https://w3c.github.io/beacon/#sec-sendBeacon-method It work for almost all the cases, but not when i close an iframe which contains my page.

这篇关于需要在navigator.sendbeacon()中进行授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆