2016-02-14 58 views
2

我正在使用服務人員推送通知。我使用XHR(阿賈克斯)的方法來得到我的通知,這裏是服務worker.js的代碼片段:爲什麼此代碼無法執行'fetch'?

var API_ENDPOINT = new Request('/getNotification', { 
redirect: 'follow'}); 

event.waitUntil(
    fetch(API_ENDPOINT, {credentials: 'include' }) 
     .then(function(response) { 

      console.log(response); 
      if (response.status && response.status != 200) { 
       // Throw an error so the promise is rejected and catch() is executed 
       throw new Error('Invalid status code from API: ' + 
        response.status); 
      } 
      // Examine the text in the response 
      return response.json(); 
     }) 
     .then(function(data) { 
      console.log('API data: ', data); 

      var title = 'TEST'; 
      var message = data['notifications'][0].text; 
      var icon = data['notifications'][0].img; 

      // Add this to the data of the notification 
      var urlToOpen = data['notifications'][0].link; 

      var notificationFilter = { 
       tag: 'Test' 
      }; 

      var notificationData = { 
       url: urlToOpen, 
       parsId:data['notifications'][0].parse_id 
      }; 

      if (!self.registration.getNotifications) { 
       return showNotification(title, message, icon, notificationData); 
      } 

     }) 
     .catch(function(err) { 
      console.error('A Problem occured with handling the push msg', err); 

      var title = 'An error occured'; 
      var message = 'We were unable to get the information for this ' + 
       'push message'; 

      return showNotification(title, message); 
     }) 
); 

此代碼工作正常,我第一次運行卷曲,但第二次我在控制檯出現錯誤:

Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': Cannot construct a Request with a Request object that has already been used 

這是什麼意思?

回答

5

的問題是,API_ENDPOINT已經由fetch()消耗。你需要一個新的請求對象,每次你通過它取得這樣clone it之前使用它:

fetch(API_ENDPOINT.clone(), { credentials: 'include' })... 
+0

謝謝你,你解決了我的問題! 對於那些誰得到一個錯誤,如: 網絡錯誤(如超時,連接中斷或無法連接的主機)發生 無法執行「取」上「ServiceWorkerGlobalScope」:不能建立與具有請求對象的請求已被使用 這是因爲您可能使用服務工作者,然後攔截抓取事件,並在內部嘗試在相同的請求後立即重新執行抓取,因爲緩存命中失敗。在這種情況下,不要執行提取(request),而是執行fetch(request.clone()),它會創建一個新的請求。 –

2

不要多次重複使用Request對象,但這樣做:

fetch('/getNotification', { 
    credentials: 'include', 
    redirect: 'follow' 
}) 
相關問題