我的代码相同。我正在调用 fetch() 但网络和服务器中的请求没有像 cookie 这样的请求标头。我又找到了一篇关于这个的帖子Service Worker 未发送请求标头 https://stackoverflow.com/questions/31567649/request-headers-not-sent-from-service-worker但它无法解决我的问题。
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);
});
})
);
});
要包含 cookie,您需要添加credentials
您的请求字段:
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)
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)