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);
});
})
);
});
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)
})
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'
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With