i have some code in vuejs and nodejs to push notification . i use service worker and web-push library.
I have this code in vuejs in help.js file :
function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
let publicKey = "BFQls47BpgbbWO44BS85Lk9ekzy7sVOQCXFteZTUwxXwpUQEKaY4hHVuUqjIxwYMStohiqYvPjH4FBctOHDOsHA"
export let send = async () => {
try {
const registration = await navigator.serviceWorker.
register('./worker.js', {scope: '/'})
let subscribe = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(publicKey)
});
console.log(subscribe);
await fetch('/subscribe', {
method: 'POST',
body:JSON.stringify(subscribe),
headers: {
'content-type': 'application/json'
}
});
} catch (err) {
console.log(err);
}
}
and in sendNotification.vue file methods I have this code:
export default{
methods : {
sendNotification() {
if ("serviceWorker" in navigator) {
console.log("send");
send(this.title, this.text);
// this.socket.emit("sendingNotification",{title:this.title,text:this.text});
}
}
}
}
and when i click on button in sendNotification.vue component sendNotification() method is fire.
this my route in nodejs using express :
let publicKey = "BFQls47BpgbbWO44BS85Lk9ekzy7sVOQCXFteZTUwxXwpUQEKaY4hHVuUqjIxwYMStohiqYvPjH4FBctOHDOsHA";
let privateKey = "wVK3KWm77rvYCaivhLXynu8l_DefDA5hBoCqNdExMes";
webPush.setVapidDetails("mailto:ash.**********@gmail.com", publicKey, privateKey);
app.post('/subscribe',(req,res)=>{
let body = req.body;
console.log(body);
let payload = JSON.stringify({"title":"hi","text":"welcome "});
webPush.sendNotification(body, payload).catch(e => console.log(e));
res.status(201).json(payload);
});
but i get this error in console :
The script has an unsupported MIME type ('text/html').
help.js?b127:37 DOMException: Failed to register a ServiceWorker for scope ('http://localhost:8080/') with script ('http://localhost:8080/worker.js'): The script has an unsupported MIME type ('text/html').
what is wrong in my code?
and another question, can I use socket.io Instead express?