Service Worker js 中的 Fetch() 无法发送请求 headers?

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

我的 same.I 代码正在调用 fetch(),但网络和服务器中的请求没有像 cookie 这样的请求 headers。我为这个 Request headers not sent from Service Worker 找到了另一个 post,但它无法解决我的问题。

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

Headers 是一个接口,您可以通过初始化为其提供一组新的选项。像这样:

 headers: new Headers({
      'Authorization': 'Bearer ' + self.token,
      'Accept': 'application/json',
      'Content-Type': 'application/json'
 })

要包含 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)
})

在浏览了service worker的官方文档后,我发现增加了

credentials: 'include'

在 fetch 中允许发送请求 headers.Thanks 以获得支持。