Reputation: 102
My app cannot connect to Firebase Realtime Database.
When I run the code below, the log 'not connected' is always printed. Moreover, the code ref.once('value', snapshot => ...)
not return any result, nor error (hanging-up forever).
Please tell me what is the problem with my code, and how to solve it. Thanks.
const firebase = require('firebase/app');
require('firebase/auth');
require('firebase/database');
const config = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "...",
appId: "..."
};
firebase.initializeApp(config);
function test() {
//Test connnection (https://firebase.google.com/docs/database/web/offline-capabilities#section-connection-state)
const connectedRef = firebase.database().ref('.info/connected');
connectedRef.on('value', (snap) => {
if (snap.val() === true) {
console.log('connected');
} else {
console.error('not connected');
}
});
//Test retrieve data.
const ref = firebase.database().ref('/');
ref.once('value', snapshot => {
const data = snapshot.val();
console.log(data);
}).catch(error => {
console.error(error);
})
}
test();
PS: This is not duplicate of Cannot connect to Firebase Realtime Database
Upvotes: 2
Views: 548
Reputation: 615
The issue maybe related to your Firewall settings, or Certification issue.
For example, if your computer use an self-signed certificate, Node.js may throw an exception self signed certificate in certificate chain
(and surprisingly Firebase client will silently ignore it without throwing up any exception, so try/catch won't work).
You can check it by adding process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
to the very first code-line of your project (note that it's for testing only, since that code may cause security problem if used in production).
Upvotes: 1