git*_*ter 2 service-worker push-api
我正在使用服务工作者进行推送通知.我正在使用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);
})
);
Run Code Online (Sandbox Code Playgroud)
这个代码在我第一次运行curl时运行正常,但第二次在控制台中出错:
Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': Cannot construct a Request with a Request object that has already been used
Run Code Online (Sandbox Code Playgroud)
这是什么意思?
问题是API_ENDPOINT已经消耗了fetch().每次将其传递给fetch时都需要一个新的请求对象,因此在使用之前克隆它:
fetch(API_ENDPOINT.clone(), { credentials: 'include' })...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4771 次 |
| 最近记录: |