为什么这段代码无法执行' fetch'?

时间:2016-02-14 17:39:46

标签: service-worker push-api

我正在使用服务工作者处理推送通知。我使用XHR(Ajax)方法来获取我的通知,这是service-worker.js的代码片段:

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

这个代码在我第一次运行curl时工作正常,但第二次在控制台中出错:

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

这是什么意思?

2 个答案:

答案 0 :(得分:6)

问题是API_ENDPOINT已经消耗了fetch()。每次传递它时都需要一个新的请求对象,以便在使用之前获取clone it

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

答案 1 :(得分:2)

不要多次重复使用Request对象,但请执行以下操作:

fetch('/getNotification', {
  credentials: 'include',
  redirect: 'follow'
})