[英]How can I get the result of a query method with mysql in nodejs?
我正在尝试在我的网站中添加通知。 我是 node.js 和服务人员的新手。 我在后端使用 expressjs 和 Mysql 数据库。
我正在关注本教程: 初学者指南 Web 使用 Service Worker 推送通知并且一切正常,直到我使用真实数据库进行 webpush 订阅。 数据已正确注册在我的表中,但是当我尝试使用 SELECT 获取这些数据以测试发送部分时,出现此错误:
C:\...\web-push-lib.js:87
throw new Error('You must pass in a subscription with at least '
^
Error: You must pass in a subscription with at least an endpoint.
我知道问题来自以下部分,但我无法找到如何使用 function 来获取查询结果。
//route to test send notification
app.get('/send-notification', (req, res) => {
//connect to the pool
pool.getConnection(function (err, connection) {
if (err) throw err; // not connected!
const sub = { subscription: null };
connection.query(`SELECT webpushsub_info FROM webpushsub`, function (err, result, fields) {
// if any error while executing above query, throw error
if (err) throw err;
// if there is no error, you have the result
sub.subscription = result;
const message = 'Inscription done';
webpush.sendNotification(sub.subscription, message)
connection.release();
res.json({ message: 'message sent' });
});
});
})
当我记录我的结果时,它返回这个。
RowDataPacket {
webpushsub_info: '{ //that's the column name where I store subscriptions
"endpoint":"https://fcm.googleapis.com/fcm/send/some_endpoint",
"expirationTime":null,
"keys":{
"p256dh":"some key",
"auth":"an other key"
}
}',
...
}
我还尝试只记录一个元素result[0].webpushsub_info
所以我得到的结果与条目完全相同。 “预期格式与 output 与 JSON 相同。在浏览器中字符串化 PushSubscription。” - npm 网络推送文档。
经过一个周末的反思,我找到了解决方案。 即使
预期格式与 output 和 JSON 相同。在浏览器中对 PushSubscription 进行字符串化。 - 网络推送的 npm 文档。
我必须 JSON.parse 结果以获取对象/数组并迭代每个结果以向所有订阅用户发送通知。
app.get('/send-notification', (req, res) => {
//connect to the pool
pool.getConnection(function (err, connection) {
if (err) throw err; // not connected!
connection.query(`SELECT webpushsub_info FROM webpushsub`, function (err, results, fields) {
// if any error while executing above query, throw error
if (err) throw err;
// if there is no error, you have the result
results.forEach(result => {
var pushSubscription = JSON.parse(result.webpushsub_info);
var message = "Post envoyé";
console.log(pushSubscription);
webpush.sendNotification(pushSubscription, message).catch(err=>console.error(err));
});
connection.release();
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.