簡體   English   中英

服務工作者js中的Fetch()無法發送請求標頭?

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

我的代碼相同。我正在調用fetch()但網絡和服務器中的請求沒有像cookie這樣的請求標頭。 我發現這個請求標題的帖子不是從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)
})

標題是一個界面,您可以通過初始化為它提供新的選項集。 像這樣的東西:

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

在瀏覽了服務工作者的官方文檔后,我注意到了

憑證:'包含'

在fetch enable中發送請求頭。但是感謝支持。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM