错误:没有创建Firebase应用程序“[DEFAULT]”-请调用Firebase App.initializeApp()

164
我有一个连接到两个应用程序的 Firebase 数据库,一个是 iOS 应用程序,另一个是使用 Node.js 编写的 Web 应用程序。Web 应用程序是一个基本算法,用于将数据设置到数据库中。每当我运行算法时,都会遇到以下错误信息:Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp().请问有人可以帮忙解决吗?
29个回答

110

你可能是在应用程序初始化之前调用firebase。所有对firebase的调用必须在.initializeApp();之后进行。

firebase.initializeApp(config);
var db = firebase.firestore();

25
这是我的问题,但不是因为代码逐行顺序,而是因为我的导入顺序。我在初始化firebase之前导入了使用firebase的代码。 - SeanMC
1
https://firebase.google.com/docs/functions/config-env?authuser=1#automatically_populated_environment_variables - ravo10
1
你说的是导入的顺序吗?我尝试了这个:import firebase from '@react-native-firebase/app'; 然后 import "@react-native-firebase/database",但它不起作用。 - Stephen Phillips
这也是我的问题,但是对我来说,这是由于在我的firebase.js文件中初始化Firebase(它从firebase导入),而在另一个模块中,我意外地从firebase导入,而不是从我的(已初始化的)./firebase - Ruben9922

31

如果您正在使用Angular,这里有一个解决方案。

完整的教程来源链接

在@ NgModule之前使用initializeApp

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { environment } from 'src/environments/environment';
import { AuthenticateService } from './services/authentication.service';
import { AngularFireAuthModule } from '@angular/fire/auth';

import * as firebase from 'firebase';

firebase.initializeApp(environment.firebase);

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule, 
    IonicModule.forRoot(), 
    AppRoutingModule,
    AngularFireAuthModule
  ],
  providers: [
    StatusBar,
    SplashScreen,
    AuthenticateService,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

38
一个与库无关的问题不应该用特定于某个库的答案来回答。 - mesqueeb
3
@mesqueeb 这可能是一个只在 Angular 中出现的错误,因此回答特定于语言也是可以的。 - Darrow Hartman
由于Angular/Firebase/Angularfire再次进行了重大更改,因此不再支持此功能。现在,您必须在导入数组中使用"provideFirebaseApp(() => initializeApp(environment.firebase))"进行初始化。在ngModule之外进行初始化现在会导致错误。现在不知道如何解决这个问题。 - undefined

23

如果您正在使用 React Native,那么如果您没有正确配置native侧,则也会发生此错误。

文档在这里:https://rnfirebase.io/

Android

首先,请下载google-services.json文件并将其放置在您的项目中的以下位置:/android/app/google-services.json

然后,在您的/android/build.gradle中添加google-services插件作为依赖项。

buildscript {
  dependencies {
    // ... other dependencies
    classpath 'com.google.gms:google-services:4.3.10'
    // Add me --- /\
  }
}

最后,通过将以下内容添加到您的/android/app/build.gradle中来执行该插件

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services' // <- Add this line

iOS

首先,通过xcode将GoogleService-Info.plist文件添加到项目中。确保它出现在构建阶段中,这样您就知道它已经添加到项目中而不仅仅是文件夹中。

然后,打开/ios/{projectName}/AppDelegate.m文件,并添加以下内容:

在文件顶部导入Firebase SDK:

#import <Firebase.h>

在现有的didFinishLaunchingWithOptions方法中,将以下内容添加到方法顶部:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // Add me --- \/
  [FIRApp configure];
  // Add me --- /\
  // ...
}

15

如果您正在使用Dart和Flutter

  1. 将firebase_core依赖项添加到pubspec.yaml中。
  2. 进入main.dart
  3. 导入'package: firebase_core / firebase_core.dart';

4.在main()中添加 async

按照我的代码操作

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  var fsconnect = FirebaseFirestore.instance;

  myget() async {
    var d = await fsconnect.collection("students").get();
    // print(d.docs[0].data());

    for (var i in d.docs) {
      print(i.data());
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: Text('Firebase Firestore App'),
      ),
      body: Column(
        children: <Widget>[
          RaisedButton(
            child: Text('send data'),
            onPressed: () {
              fsconnect.collection("students").add({
                'name': 'sarah',
                'title': 'xyz',
                'email': 'sarah@gmail.com',
              });
              print("send ..");
            },
          ),
          RaisedButton(
            child: Text('get data'),
            onPressed: () {
              myget();
              print("get data ...");
            },
          )
        ],
      ),
    ));
  }
}

1
这对你有用吗?我尝试在Main中添加async,但无法解决问题。现在我遵循此链接(https://firebase.flutter.dev/docs/overview/#initializing-flutterfire)。该链接也无法解决问题。出现Firebase未初始化的错误。 - Vikrant Agrahari
1
那个解决方案对我也没用。我按照这个视频 https://www.youtube.com/watch?v=Z0jFkP0A3B0 做了一切正确的事情,但不幸的是我仍然收到错误信息... - Tom

8

我在遵循Firebase在线指南(链接)时遇到了类似的问题。

“初始化多个应用程序”的章节标题有误导性,因为该标题下的第一个示例实际上展示了如何初始化单个默认应用程序。以下是该示例:

// Initialize the default app
var defaultApp = admin.initializeApp(defaultAppConfig);

console.log(defaultApp.name);  // "[DEFAULT]"

// Retrieve services via the defaultApp variable...
var defaultAuth = defaultApp.auth();
var defaultDatabase = defaultApp.database();

// ... or use the equivalent shorthand notation
defaultAuth = admin.auth();
defaultDatabase = admin.database();

如果你正在从早期的2.x SDK迁移,你需要按照以上所示更新访问数据库的方式,否则你将会遇到'No Firebase App '[DEFAULT]'错误。
Google在以下链接中提供更好的文档:
1. 初始化:https://firebase.google.com/docs/database/admin/start 2. 保存数据:https://firebase.google.com/docs/database/admin/save-data 3. 检索数据:https://firebase.google.com/docs/database/admin/retrieve-data

7
我的问题是因为我添加了第二个参数:
AngularFireModule.initializeApp(firebaseConfig, 'reservas')

如果我删除第二个参数,它就能正常工作:

AngularFireModule.initializeApp(firebaseConfig)

使用firebase.initializeApp和AngularFireModule.initializeApp有什么区别吗? - D.Hodges
1
第二个参数创建了一个新的“app”句柄。如果省略该参数,则意味着应用程序名称为[DEFAULT],因此是“默认应用程序”。这对您很重要的原因可能是代码可以通过例如firebase.firestore()隐式使用默认值,而使用自定义“app”(第一个)时,必须传递返回值,“app句柄”。我两种方式都使用。主Web应用程序使用默认值,库中使用命名变量。 - akauppi

6

这可能不是最佳答案,但我必须像下面这样使用管理员和Firebase来初始化应用程序。 我使用管理员来完成自己的目的,也使用Firebase。

const firebase = require("firebase");
const admin = require("firebase-admin");

admin.initializeApp(functions.config().firebase);
firebase.initializeApp(functions.config().firebase);
// Get the Auth service for the default app
var authService = firebase.auth();

 function createUserWithEmailAndPassword(request, response) {
        const email = request.query.email;
        const password = request.query.password;
        if (!email) {
            response.send("query.email is required.");
            return;
        }
        if (!password) {
            response.send("query.password is required.");
            return;
        }
        return authService.createUserWithEmailAndPassword(email, password)
            .then(success => {
                let responseJson = JSON.stringify(success);
                console.log("createUserWithEmailAndPassword.responseJson", responseJson);
                response.send(responseJson);
            })
            .catch(error => {
                let errorJson = JSON.stringify(error);
                console.log("createUserWithEmailAndPassword.errorJson", errorJson);
                response.send(errorJson);
            });
    }

4

如果你正在使用React Native并且开发IOS应用,那么我认为你可能忘记了链接Firebase模块的步骤。

请按照以下步骤进行:

打开/ios/{projectName}/AppDelegate.m文件,并添加以下内容:

在文件顶部导入Firebase SDK:

#import <Firebase.h>

在您现有的didFinishLaunchingWithOptions方法中,将以下内容添加到该方法的顶部:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // Add this  --- \/
  if ([FIRApp defaultApp] == nil) {
    [FIRApp configure];
  }
  // Add me --- /\
  // ...
}

4

Flutter Web

对于我来说,当我以“release”模式运行我的应用程序时出现了错误。

flutter run -d chrome --release

并且当我在Firebase托管上部署应用程序时也出现了错误。

firebase deploy

解决方案

由于我在index.html中初始化了Firebase,所以我必须改变firebase和main.dart.js的实现顺序。

<script>
  var firebaseConfig = {
  apiKey: "xxxxxxxxxxxxxxxxxxxxxx",
  authDomain: "xxxxxxxxxxx.firebaseapp.com",
  databaseURL: "https://xxxxxxxxxx.firebaseio.com",
  projectId: "xxxxxxxxxxx",
  storageBucket: "xxxxxxxx.appspot.com",
  messagingSenderId: "xxxxxxxxxxx",
  appId: "1:xxxxxxxxxx:web:xxxxxxxxxxxxx",
  measurementId: "G-xxxxxxxxx"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  firebase.analytics();
</script>

//moved below firebase init
<script src="main.dart.js" type="application/javascript"></script>

1
这解决了这个问题。 - Dario Brux

3

这个答案可能已经在别处给出,但这是我对这个错误的看法,这个错误可能由多种原因引起

  1. 默认应用程序在其他应用程序之后初始化。正确的方法是先初始化默认应用程序,然后再初始化其它应用程序。
  2. firebase.apps.app() 在初始化默认应用程序之前被调用。这段代码基本上返回默认应用程序实例。由于它不存在,因此会出现错误。
  3. 最后,您在应用程序初始化之前初始化了其他 Firebase 服务,例如身份验证、数据库、Firestore 等。

对我来说是第三个。我已经命名了导出{firebaseClient,dbClient,authClient,storageClient},其中单独的服务被定义为const dbClient = firebaseClient.firestore(); ... - arunmenon
没听说过1。会去查一下! - akauppi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接