问题描述
我的问题是,当我调用一个侦听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() https://w3c.github.io/beacon/#sec-sendBeacon-method 它适用于几乎所有情况,但当我关闭包含我的页面的iframe时无效.
Aparently, if we must use a token connexion, we can't use navigator.sendbeacon() https://w3c.github.io/beacon/#sec-sendBeacon-methodIt work for almost all the cases, but not when i close an iframe which contains my page.
这篇关于需要在navigator.sendbeacon()中进行授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!