3

我的代碼是相同的。我調用fetch(),但網絡和服務器中的請求沒有cookie等請求標頭。我發現這個Request headers not sent from Service Worker更多的帖子,但它無法解決我的問題。服務工作者js中的Fetch()無法發送請求標頭?

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

我有同樣的問題,但我不認爲在上面的代碼中用戶/獲取通知的用途是什麼。 –

+0

你是什麼意思self.token? –

回答

-2

,我注意到另外的

憑證:'包括'

在fetch enable中發送請求頭。儘管如此,感謝支持。

1

頭是一個接口,您可以通過初始化提供一組新的選項。事情是這樣的:

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

要包括你需要的credentials字段添加到您的請求中的Cookie:瀏覽服務工作者的正式文件後,那麼

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) 
}) 
相關問題