2017-05-04 146 views
0

我试图将数据从服务器传递给服务人员,但数据对服务人员来说是空的。如何将数据从服务器传递给服务人员

这里是我的代码:

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

但标题是不是被认可。我如何将数据从我的服务器传递给服务人员?

回答

1

在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。你的公钥在服务器和客户端应该是相同的。