Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch() in service worker js not able to send request headers?

My code for the same.I am calling fetch() but the request in network and server has no request headers like cookie. I found one more post for this Request headers not sent from Service Worker but it was not able to solve my problem.

self.addEventListener('push', function (event) {
  event.waitUntil(
    self.registration.pushManager.getSubscription().then(function (subscription) {
      fetch('/user/get-notification', {
        mode: 'no-cors',
        method: 'post',
        headers: {
          'Authorization': 'Bearer ' + self.token,
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(subscription)
      }).then(function (response) {
        if (response.status != 'success') {
          console.log('Looks like there was a problem. Status Code: ' + response.status);
          throw new Error();
        }

        return response.json().then(function (data) {
          var title = data.title;
          var message = data.message;
          var icon = data.image;

          return self.registration.showNotification(title, {
            body: message,
            icon: icon
          });
        });
      }).catch(function (err) {
        console.error('Unable to retrieve data', err);
      });
    })
  );
});
like image 864
Rahul Kathuria Avatar asked Oct 21 '25 19:10

Rahul Kathuria


2 Answers

To include cookies you need to add the credentials field to your request:

fetch('/user/get-notification', {
  credentials: 'include', // <-- To include cookies!
  mode: 'no-cors',
  method: 'post',
  headers: {
    'Authorization': 'Bearer ' + self.token,
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(subscription)
})
like image 147
Salva Avatar answered Oct 24 '25 07:10

Salva


Headers is an interface, you can provide new set of options to it, by initializing. Something like this:

 headers: new Headers({
      'Authorization': 'Bearer ' + self.token,
      'Accept': 'application/json',
      'Content-Type': 'application/json'
 })
like image 32
anshulix Avatar answered Oct 24 '25 09:10

anshulix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!