2

我正在使用服务人员处理推送通知。我正在使用 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

这是什么意思?

4

2 回答 2

7

问题是API_ENDPOINT已经被fetch(). 每次将请求对象传递给 fetch 时,您都需要一个新的请求对象,因此请在使用它之前对其进行克隆

fetch(API_ENDPOINT.clone(), { credentials: 'include' })...
于 2016-02-15T16:58:35.530 回答
2

不要多次重用 Request 对象,但要:

fetch('/getNotification', {
  credentials: 'include',
  redirect: 'follow'
})
于 2016-02-15T16:56:14.497 回答