2
我正在使用服务人员推送通知。我使用XHR(阿贾克斯)的方法来得到我的通知,这里是服务worker.js的代码片段:为什么此代码无法执行'fetch'?
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);
})
);
此代码工作正常,我第一次运行卷曲,但第二次我在控制台出现错误:
Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': Cannot construct a Request with a Request object that has already been used
这是什么意思?
谢谢你,你解决了我的问题! 对于那些谁得到一个错误,如: 网络错误(如超时,连接中断或无法连接的主机)发生 无法执行“取”上“ServiceWorkerGlobalScope”:不能建立与具有请求对象的请求已被使用 这是因为您可能使用服务工作者,然后拦截抓取事件,并在内部尝试在相同的请求后立即重新执行抓取,因为缓存命中失败。在这种情况下,不要执行提取(request),而是执行fetch(request.clone()),它会创建一个新的请求。 –