Uncaught [firebase_messaging/failed-service-worker-registration] Messaging: We are unable to register the default service worker - flutter-web

flutter web
I am getting this error in live flutter web project.
Uncaught [firebase_messaging/failed-service-worker-registration] Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('https://jordanaqqar.com/firebase-cloud-messaging-push-scope') with script ('https://jordanaqqar.com/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script.
Error image
Here is my index.html
<!DOCTYPE html>
<html>
<head>
<!--
If you are serving your web app in a path other than the root, change the
href value below to reflect the base path you are serving from.
The path provided below has to start and end with a slash "/" in order for
it to work correctly.
Fore more details:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
-->
<base href="/appname/">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Property aplication.">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="app_name">
<meta name="google-signin-client_id" content="client_key">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png" />
<title>jordan_aqqar</title>
<link rel="manifest" href="manifest.json">
<script src="https://maps.googleapis.com/maps/api/js?key=KEY"></script>
</head>
<body>
<!-- This script installs service_worker.js to provide PWA functionality to
application. For more information, see:
https://developers.google.com/web/fundamentals/primers/service-workers
-->
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.8.0/firebase-messaging.js"></script>
<!--<script src="https://www.gstatic.com/firebasejs/firebase/8.8.0/firebase-messaging.js"></script>-->
<script src="https://www.gstatic.com/firebasejs/8.8.0/firebase-auth.js"></script>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('flutter-first-frame', function () {
navigator.serviceWorker.register('/appname/firebase-messaging-sw.js');
});
}
</script>
<!-- Firebase Configuration -->
<script>
var firebaseConfig = {
apiKey: "APIKEY",
authDomain: "AUTHDOMAIN",
projectId: "PROJECTID",
storageBucket: "STORAGEBUCKET",
messagingSenderId: "MESSAGINGSENDERID",
appId: "APPID",
measurementId: "MEASUREMENTID"
};
firebase.initializeApp(firebaseConfig);
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
and this is firebase-messaging-sw.js file
importScripts("https://www.gstatic.com/firebasejs/8.8.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/8.8.0/firebase-messaging.js");
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
firebase.initializeApp({
apiKey: "APIKEY",
authDomain: "AUTHDOMAIN",
projectId: "PROJECTID",
storageBucket: "STORAGEBUCKET",
messagingSenderId: "MESSAGINGSENDERID",
appId: "APPID",
measurementId: "MEASUREMENTID"
});
// Initialize Firebase
firebase.analytics();
// Retrieve firebase messaging
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
const promiseChain = clients
.matchAll({
type: "window",
includeUncontrolled: true
})
.then(windowClients => {
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
windowClient.postMessage(payload);
}
})
.then(() => {
return registration.showNotification("New Message");
});
return promiseChain;
});
self.addEventListener('notificationclick', function (event) {
console.log('notification received: ', event)
});

Related

script source not found, in node.js when trying https connection

im trying to reference socket.io in my login.html but it gives following error:
GET https://localhost:3000/socket.io.js net::ERR_ABORTED 404 (Not Found)
i think its because this code line in my login.html :
<script src='/client-dist/socket.io.js'></script>
i was trying other reference the script in other ways, but those doesnt work. it worked when my server.js was a http connection, but now i need a https connection.
its also dont possible to reference oder javascript refrences.
login.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<section>
<h1>Login</h1>
<p>
username:<input id="username">
<br>
password:<input id="password">
<br>
</p>
<p>
<button onclick="window.location.href='/register'">Create Account</button>
</p>
<button id="submitButtonLogin" onclick="onClick()">submit</button>
</section>
<script src='/client-dist/socket.io.js'></script>
</body>
</html>
server.js:
const express= require('express')
const app= express();
//const path= require('path')
const https= require('https')
const io=require('socket.io')(https,{maxHttpsBufferSize:1e8})
const fs=require('fs')
const sslServer =https.createServer({
key: fs.readFileSync('cert/key.pem'),
cert: fs.readFileSync('cert/cert.pem')
},app)
const PORT=process.env.PORT || 3000
sslServer.listen(PORT, ()=>{
console.log(`listening to port ${PORT}`)
});sslServer.setTimeout(0)
app.get('/test', (req,res)=>{
res.sendStatus(200);
})
app.use(express.static(__dirname + '/public'))
app.use(require('./routes/posts'));
app.use(require('./routes/users'));
app.get('/',(req,res)=>{
res.sendFile(__dirname + '/login_register/login.html')
})
app.get('/register',(req,res)=>{
res.sendFile(__dirname + '/login_register/register.html')
})
app.get('/chatroom',(req,res)=>{
res.sendFile(__dirname + '/index.html')
})
my hierarchy:
chatapplication
-cert
cert.pem
csr.pem
key.pem
-login_register
login.html
register.html
-model
user.js
-node_modules
(included when setup)
-public
client.js
style.css
-routes
users.js
database.js
index.html
package-lock.json
package.json
secret.json
server.js

Can't find my image files while deploying my node js web app on Heroku

I have deployed my web app on Heroku, but Heroku's sever can't find my image file located in the static folder.
This is my app.js file....
const express=require("express");
const body=require("body-parser");
const http=require("http");
var path = require('path');
const app=express();
var temp="";
var des="";
var city_name="";
var src="";
var cn="";
var temp_max="";
var temp_min="";
app.use(express.static(path.join(__dirname, 'public')));
app.use(body.urlencoded({extended:true}));
app.set('views', path.join(__dirname, 'views'));
app.set("view engine","ejs");
app.get("/",(req,res)=>{
res.sendFile(__dirname+"/index.html");
})
app.post("/",(req,res)=>{
var city=req.body.city;
var country=req.body.country;
var date = new Date();
var api_key="4aa7299408553a0ec003e1dd56d73cf5";
var url="http://api.openweathermap.org/data/2.5/weather?units=metric&q="+ city +","+country+"&appid=";
http.get(url+api_key,(response)=>{
console.log(response.statusCode);
response.on("data",(data)=>{
var s=JSON.parse(data);
temp=s.main.temp;
city_name=city;
temp_max=s.main.temp_max;
temp_min=s.main.temp_min;
cn=country;
console.log(s);
des=s.weather[0].main;
src=des+".png";
console.log(src);
res.redirect("/weather");
})
})
})
app.get("/weather",(req,res)=>{
res.render("weather",{temp: temp,city: city_name,des: des,src: src,country: cn,temp_max: temp_max,temp_min: temp_min});
})
app.listen(process.env.PORT || 3000,()=>{
console.log("Port 3000");
})
My file structure....
|--public
|--images
|--css
|--views
|--weather.ejs
|--app.js
|--index.html
|--package.json
My weather.ejs file--
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weahter</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="css/weather.css">
</head>
<body>
<div class="box">
<p><h2><%= city %>, <%= country %></h2></p>
<p><img src='images/<%= src %>' alts="Des"></p>
<p><h4><%= temp %>°C</h4></p>
<p class="temp"><span><%= temp_min %>°C</span> <span><%= temp_max %>°C</span></p>
<p><h3><%= des %></h3></p>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
It gives the following error....
Failed to load resource: the server responded with a status of 404 (Not Found)
Its works fine on my localserver.
I am very much worried about this problem.
Please help me.
try this code
<p><img src='./public/images/<%= src %>' alts="Des"></p>

NodeJS app works locally but not when deployed on firebase

I am trying to deploy a nodeJS app on firebase using this tutorial "https://www.youtube.com/watch?v=LOeioOKUKI8&t=437s", I followed exactly what was told and the app worked as intended locally using "firebase serve" but when I deployed it, POST and GET request stopped working i.e. client side code is unable to reach server side.
for example, on loading "appURL/temp" I'm getting "Content Security Policy: The page’s settings blocked the loading of a resource" error.
What I'm actually trying to do : to send JSON data from Client to server, process the data and return some result as response
What currently app does: takes input, sends it to the server on click and receive it back as response to the POST request
on Client Side (public/index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script defer src="/__/firebase/7.14.6/firebase-app.js"></script>
<script defer src="/__/firebase/init.js"></script>
</head>
<body>
<h1>Home</h1>
<input type="text" id="ip">
<button onclick="send()">send</button>
<div id="text"></div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
let textDiv = document.getElementById("text")
function send(){
let ip = document.getElementById("ip").value;
axios.post('/home',ip)
.then( resp => {
textDiv.innerHTML = JSON.stringify(resp.data);
})
}
</script>
</body>
on Server Side (functions/index.js
const func = require('./add'); //this is just to wrap the string with brackets
const functions = require('firebase-functions');
const express = require('express');
const multer = require('multer');
const upload = multer();
const app = express();
app.get('/temp', (req, resp) => {
resp.send("GET Works");
console.log("GET");
})
app.post('/home', upload.single("data"), (req, res) => {
console.log(func.add(JSON.stringify(req.body)))
res.send(func.add(JSON.stringify(req.body)))
});
exports.app = functions.https.onRequest(app);
firebase.json
{
"hosting": {
"public": "public",
"rewrites":[{
"source": "**",
"function": "app"
}],
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
}
}
Directory Structure
Versions
node : 13.6.0
express : 6.13.4
mutler : 6.13.4

How to resolve "Unresolved variable or type data" warnings when using EJS?

I'm using EJS as Template engine. Everything looks like working fine, but I have these weak "Unresolved variable or type data" warnings in IntelliJ. How to get rid of these warnings? Is anything wrong with the code?
app.js:
var express = require('express');
var app = express();
var hostname = 'localhost';
var port = 3000;
app.set('view engine', 'ejs');
app.use('/static', express.static('static'));
app.get('/', (req, res) => {
res.sendFile(`${__dirname}/index.html`);
});
app.get('/profile/:id', (req, res) => {
var userData = {
id: req.params.id,
firstName: 'John',
lastName: 'Peterson',
age: 23,
active: true,
interests: ['Design', 'Web', 'Acting']
};
res.render('profile', { data: userData });
});
app.get('*', (req, res) => {
res.sendFile(`${__dirname}/404.html`);
});
app.listen(port);
console.log(`Server running at http://${hostname}:${port}`);
views/profile.ejs:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My Profile</title>
<link rel="stylesheet" href="../static/style.css">
</head>
<body>
<h2>My Profile Template</h2>
<p>ID: <%=data.id%></p>
<p>Name: <%=data.firstName%> <%=data.lastName%></p>
<p>Age: <%=data.age%> years</p>
<p>Active: <%=data.active%></p>
</body>
</html>
I solved this problem, by adding spaces between %=%.
<p>Name: <%= data.firstName %> <%= data.lastName %></p>
It looks like you need to export the data object somewhere in your code.
Try to add module.exports = { data: {}; } to the end of your app.js file.
To make autocomplete work correctly, you should either export a real object (userData) instead of an empty one, or use TypeScript.

Nodejs client button without redirect

I have a nodejs app that acts as a remote control for Cmus music player. It uses a route for each function ie /play /next etc. This works fine, but with each button click I must call res.redirect("index.html") which obviously causes the page to reload. How can I perform this so that each button click is still able to send the command to the server but not reload the page?
server.js
var express = require('express');
var app = express();
var path = require('path');
var exec = require('child_process').exec;
var Commands = require('./commands.js');
var child;
app.use(express.static(__dirname + '/public'));
//Routes
app.get('/', function (req, res){
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/play', function(req, res){
// console.log(req);
handleCommand(Commands.PAUSE);
res.redirect("index.html");
});
var server = app.listen(8080, function () {
console.log("Server online");
console.log(commands.NEXT);
});
function handleCommand(command) {
child = exec(command, function (error, stdout, stderr) {
// sys.print('Stdout ' + stdout);
// sys.print('Stderr ' + stderr);
if (error !== null) {
console.log('ERROR: ' + error);
}
})
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cmus Remote</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="client.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body id="body">
<form action="/play">
<input id="play" type="submit" value="⏯">
</form>
</table>
</body>
</html>
Instead of using a form to "submit" the button, you can attach event handlers to the button that will do a POST request without reloading the page. Then, you won't need to send any redirects at all. Since you have JQuery on the page, I'll give an example with JQuery.
Index.html
<button id="play">Play</button>
<!-- Other code -->
<!-- Script or external JS code -->
<script>
$('#play').click(function(){
$.post('/play');
});
</script>

Resources