6

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.

Here my actual code:

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

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

jcalz
  • 264,269
  • 27
  • 359
  • 360
scavengers
  • 221
  • 2
  • 9

2 Answers2

10

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),
      });
}

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.

scavengers
  • 221
  • 2
  • 9
2

Try this:

  let headers = {
    Authorization: 'Bearer ' + token
  };
  let blob = new Blob([JSON.stringify(infoIWantToSent)], headers);
  navigator.sendBeacon('url', blob);
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
  • 1
    Thank you for you response. Unfortunaly, I have this error in compilation with your method : error TS2559: Type '{ Authorization: string; }' has no properties in common with type 'BlobPropertyBag'. I tried to add a type lyke this ``` const headers = { type: 'application/json', Authorization: 'Bearer ' + this.getUser().token }; ``` But it's ot working either. – scavengers May 14 '19 at 14:10
  • 1
    I would have said to include ` type: 'application/json'`, but since you have tried it already, I don't have anymore input. Sorry. Let me know the solution once you crack it. All the best – Adrita Sharma May 14 '19 at 14:22