[英]How to get a variable from front to a service worker?
我创建了一个服务工作者来向注册用户发送通知。
它运作良好,直到我尝试为每个注册到服务工作者(发送通知)的人实现一种 id。
我这样做是因为我必须从我的数据库中删除旧的注册,所以我选择让每个用户进行三个注册(一个用于移动设备,另外两个用于计算机上的不同导航器),如果还有更多,我想从中删除数据库越旧。
我正在为数据库使用 nodejs、express 和 mySql。
当我启动订阅时出现此错误:
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
我在另一篇文章中看到,这是因为他们尝试 JSON.parse 已经是 object 的内容。
但就我而言,我找不到解析的位置,请参阅相关部分:
// service.js (service worker file)
// saveSubscription saves the subscription to the backend
const saveSubscription = async (subscription, usrCode) => {
const SERVER_URL = 'https://mywebsite:4000/save-subscription'
subscription = JSON.stringify(subscription);
console.log(subscription); // I got here what I expect
console.log(usrCode); // <-------------------------------- HERE I GOT UNDEFIND
const response = await fetch(SERVER_URL, {
method: 'post',
headers: {
'Content-Type' : 'application/json',
},
body : {
subscription: subscription,
usrCode: usrCode
}
})
return response
}
但是当我在检查器中使用 console.log(usrCode) 时,我得到了很好的价值。
那么我应该如何获取service.js中的值
也许问题来自:
const bodyParser = require('body-parser')
app.use(bodyParser.json())
一开始我以为问题出在后面(因为我不太擅长异步功能)。
这是背面,如果我弄错了。
// index.js (backend)
// Insert into database
const saveToDatabase = async (subscription, usrCode) => {
// make to connection to the database.
pool.getConnection(function (err, connection) {
if (err) throw err; // not connected!
console.log(usrCode);
console.log(subscription);
connection.query(`INSERT INTO webpushsub (webpushsub_info, webpushsub_code) VALUES ('${subscription}', '${usrCode}')`, 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
console.log(result);
connection.release();
});
});
}
// The new /save-subscription endpoint
app.post('/save-subscription', async (req, res) => {
const usrCode = req.body.usrCode; // <------------------ I'm not sure about this part
const subscription = req.body.subscription
await saveToDatabase(JSON.stringify(subscription, usrCode)) //Method to save the subscription to Database
res.json({ message: 'success' })
})
通过在谷歌上搜索,我找到了这个教程。 所以 usrCode 未定义的原因是因为 service worker 无法访问存储在前面的数据。 首先,您必须按以下方式在 URL 中传递它:
// swinstaller.js (front)
// SERVICE WORKER INITIALIZATION
const registerServiceWorker = async (usrCode) => {
const swRegistration = await navigator.serviceWorker.register('service.js?config=' + usrCode); //notice the file name
return swRegistration;
}
然后在服务工作者中获取它:
// service.js (service worker file)
// get the usrCode
const usrCode = new URL(location).searchParams.get('config');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.