我试图将数据从服务器传递给服务工作者,但数据将为空。
这是我的代码:
var webpush = require('web-push');
var message = sendData.message;
var subscription_info = sendData.subscription_info;
webpush.setVapidDetails(
'mailto:xxx',
public_key,
private_key
);
webpush.setGCMAPIKey('xxx');
webpush.sendNotification(subscription_info, String(message));这是console.log(消息):
{ text: 'message',
title: 'title',
icon_image: 'http://google.com/xxx.jpg',
link: 'www.google.com' }这位是我的服务生
self.addEventListener('push', function(event) {
var title = event.data.title;
var options = {
body: event.data.text,
requireInteraction: true
};
event.waitUntil(self.registration.showNotification(title, options));
});但是头衔并没有被认可。如何将数据从服务器传递给服务工作人员?
发布于 2017-05-17 11:05:25
尝试在NodeJS端执行以下代码。缺少将JSON消息对象转换为缓冲区(二进制)的方法。
var webpush = require('web-push');
var message = sendData.message;
var subscription_info = sendData.subscription_info;
webpush.setVapidDetails(
'mailto:xxx',
<Vapid public key>,
<Vapid private key>
);
webpush.setGCMAPIKey('xxx');
message = new Buffer.from(JSON.stringify(message)); // missing code.
webpush.sendNotification(subscription_info, String(message));在订阅服务工作者时,您需要发送加密的公钥并发送订阅请求,并使用它从服务器发送推送通知。
const vapidPublicKey = '<Vapid public key>';
const convertedVapidKey = urlBase64ToUint8Array(vapidPublicKey);
registration.pushManager.subscribe({
userVisibleOnly: true, //Always show notification when received
applicationServerKey: convertedVapidKey
})
.then(function (subscription) {
console.log(subscription) // use this subscription info on server side
console.info('Push notification subscribed.');
})
.catch(function (error) {
console.error('Push notification subscription error: ', error);
});PS.您的公钥在服务器端和客户端应该是相同的。
https://stackoverflow.com/questions/43783786
复制相似问题