javascript - 不发送推送通知
问题描述
我对推送通知有疑问。我在firebase函数日志中有这个错误:
错误:要发送带有有效负载的消息,订阅必须具有“auth”和“p256dh”键。
exports.storePostData = functions.https.onRequest(
(request, response) => {
cors(request, response, () => {
admin.database().ref('posts').push({
id: request.body.id,
title: request.body.title,
location: request.body.location,
image: request.body.image
}).then(() => {
webpush.setVapidDetails('mailto: xxxx@gmail.com', 'BLl7xIPAyJNzsMi5vo_aG-4RdXdyZ4Q4ZFpTgnm902qN79MIiSORBk9N-rfFEGiKNPuJu5SJmUX35Wwce9nuH94', 'M8E6hw7jCmu7qNQJ88FV5o02OAiLefEFJK8jyJimk7g')
return admin.database().ref('subscriptions').once('value');
}).then(subscriptions => {
subscriptions.forEach(sub => {
var pushConfig = {
endpoint: sub.val().endpoint,
keys: {
auth: sub.val().keys,
p256dh: sub.val().p256dh
}
}
webpush.sendNotification(pushConfig, JSON.stringify({
title: 'New Post',
content: 'New post added',
openUrl: '/help'
})).catch(err => {
console.log(err)
})
})
response.status(201).json({
message: 'Data stored',
id: request.body.id
})
}).catch(err => {
response.status(500).json({
error: err
})
})
})
});
这是我用于存储帖子数据的功能,我认为问题出在这里,因为它甚至无法在 serviceWorker 中推送事件(我在那里没有任何日志)。
解决方案
在客户端,您应该能够在 Angular 上检索订阅,就像
const sw = await navigator.serviceWorker.register('/assets/js/service-worker.js', { scope: '/assets/js/' });
let subscription = await sw.pushManager.getSubscription();
通过这种方式,您应该可以获取订阅,并且订阅对象包含 p256dh 和 auth 密钥。
您应该能够通过以下方式查看值
console.log("subscription: ", subscription?.toJSON());
推荐阅读
- javascript - 带日期对象的 setTimeout
- java - 遍历方法时发生 NullPointerException
- google-cloud-vision - 我可以将 Google Vision 配置为识别粗俗分数符号(例如 ½、¼ 等...)吗?
- xslt - 如何按不同标签的值分组?
- javascript - Firebase 与 Angular:从查询中排除字段
- parallel-processing - kubernetes 不跟踪作业完成的 pod 成功计数
- mysql - 如何在 ASP.Net Core 2.1 中访问基于 .Net Identity 2 构建的 Mysql 数据库
- arrays - 循环并将单元格值放入其中后,VBA数组为空
- php - 当我在 localhost 中运行 codeigniter 时,会自动下载 index.php 文件
- javascript - Javascript 日期对象为不同格式的日期字符串提供不同的时区