Why does this code fail to execute 'fetch'?

馋奶兔 提交于 2019-12-21 21:35:26

问题


I'm working on push notifications using service workers. I'm using the XHR(Ajax) approach to get my notification, here is a code snippet of 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);
        })
);

This code works fine the first time I run the curl, but the second time I got an error in the console:

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

What does this mean?


回答1:


The problem is that API_ENDPOINT has already consumed by the fetch(). You need a fresh request object each time you pass it to fetch so clone it before using it:

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



回答2:


Don't reuse the Request object multiple times, but do:

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


来源:https://stackoverflow.com/questions/35394924/why-does-this-code-fail-to-execute-fetch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!