为什么此代码无法执行“获取"? [英] Why does this code fail to execute 'fetch'?

查看:58
本文介绍了为什么此代码无法执行“获取"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Service Worker 处理推送通知.我正在使用 XHR(Ajax) 方法来获取通知,这里是 service-worker.js 的代码片段:

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

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

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

这是什么意思?

推荐答案

问题是 API_ENDPOINT 已经被 fetch() 消费了.每次传递它时都需要一个新的请求对象来获取所以 clone 使用前:

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

这篇关于为什么此代码无法执行“获取"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆