Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k views
in Technique[技术] by (71.8m points)

javascript - TypeError: Cannot read property 'ref' of undefined

I am trying to use Firebase in my Nodejs project but I keep getting an error and I cannot figure it out.

my firebase.ts

import firebase from 'firebase/app'
import "firebase/database"
const config = {
  apiKey: "xxxxx",
  authDomain: "xxxx.firebaseapp.com",
  databaseURL: "https://xxxxx.firebaseio.com",
  projectId: "xxxxx",
  storageBucket: "xxxxx.appspot.com",
  messagingSenderId: "xxxxx",
  appId: "xxxxx"
};
firebase.initializeApp(config);
export const databaseRef = firebase.database();
export default firebase;

index.ts

export * from './firebase';

Where it is used

import { databaseRef } from '../../common/services/firebase'

await databaseRef.ref('dummy')

I got this error

TypeError: Cannot read property 'ref' of undefined


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Instead of exporting firebase.database() first, try exporting firebase.initializeApp(config)

If the file is to be loaded a second time, check for the existing firebase app instance first.

I am using Firebase Cloud Messaging but the logic should be similar:

// Dependencies
const firebase = require('firebase-admin');

// Service account creds
const serviceAccount = require('../../creds/creds.json');

// Initalize the firebase app
const config = {
    credential: firebase.credential.cert(serviceAccount),
};

// Check for existing firebase app instance
if (!firebase.apps.length) {
    // Create a new one if there is none
    const fb = firebase.initializeApp(config);
    module.exports = { fb, };
} else {
    // otherwise export the existing one
    const fb = firebase.app();
    module.exports = { fb, };
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...