我的代码相同。我正在调用 fetch() 但网络和服务器中的请求没有像 cookie 这样的请求 header 。我又找到了一个帖子 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)
})
关于javascript - 服务 worker js 中的 Fetch() 无法发送请求 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37437047/