我正在使用NodeJs后端服务器,而对于我的前端Web应用程序,我使用的是Vue-CLI。后端位于localhost的一个端口,以及开发模式下另一个端口上的前端应用程序。
我试图通过使用web-push npm和Vue CLI附带的服务工作者来实现推送通知。但是,我不知道应该将eventListener用于'push'。
我尝试在(frontend /)主目录(registerServiceWorker.js所在的位置)创建一个名为'service-worker.js'的文件。在下面的代码中,我只是将eventListener放在registerServiceWorker.js文件中。
提前致谢!
前端(registerServiceWorker.js):
/* eslint-disable no-console */
console.log('baseURL:', process.env.BASE_URL)
const BACKEND_SUBSCRIBE = (process.env.NODE_ENV !== 'development')
? '/subscribe'
: '//localhost:3003/subscribe';
import { register } from 'register-service-worker'
import {convertedVapidKey} from './services/PushNotificationService'
import Axios from 'axios';
const axios = Axios.create({
withCredentials: true
});
self.addEventListener('push', function(e) {
console.log('Hi');
const data = e.data.json();
self.registration.showNotification(data.title, {
body: 'Notified by me',
icon: 'icon'
});
});
if (process.env.NODE_ENV === 'development') {
register(`${process.env.BASE_URL}service-worker.js`, {
ready (sw) {
sw.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: convertedVapidKey
}).then(sub => {
console.log('sending sub', sub)
axios.post(BACKEND_SUBSCRIBE, sub)
.then(res => {
console.log('sent sub,', res)
});
})
},
后端(server.js):
const webpush = require('web-push');
const publicKey= 'keystring';
const privateKey = 'keystring'
webpush.setVapidDetails(
'mailto:[email protected]',
publicKey,
privateKey
)
app.post('/subscribe', (req, res) => {
const subscription = req.body;
console.log(subscription);
// send 201 status
res.status(201).json({'see':'see this?'});
// create payload
const payload = JSON.stringify({ title: 'Push test'});
webpush.sendNotification(subscription, payload)
.catch(err => console.log(err));
})
在经历了所有头痛之后,我要做的就是在主要前端配置一个“vue.config.js”文件,如下所示:
// vue.config.js
module.exports = {
pwa: {
workboxPluginMode: 'InjectManifest',
workboxOptions: {
swSrc: 'src/service-worker.js'
},
themeColor: '#8bc34a'
},
}
这允许我将我的push事件监听器粘贴到src / service-worker.js文件中:)