Why does this code fail to execute 'fetch'

2020-07-26 10:56发布

问题:

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