简体   繁体   English

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

[英]Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()

I have a firebase database linked up to two apps, one being an iOS app and another being a web app coded in node.js which is a basic algorithm that sets data to the database. I have a firebase database linked up to two apps, one being an iOS app and another being a web app coded in node.js which is a basic algorithm that sets data to the database. When ever i am running the algorithm i am confronted with-每当我运行算法时,我都会遇到-

Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp().错误:没有 Firebase 应用程序“[DEFAULT]”已创建 - 调用 Firebase App.initializeApp()。 at Error (native) at R (/Users/dd/Desktop/Code/NODE/node_modules/firebase/app-node.js:22:335) at a (/Users/dd/Desktop/Code/NODE/node_modules/firebase/app-node.js:20:68) at Object.c [as database] (/Users/dd/Desktop/Code/NODE/node_modules/firebase/app-node.js:21:447) at Object.在 R (/Users/dd/Desktop/Code/NODE/node_modules/firebase/app-node.js:22:335) 在 (/Users/dd/Desktop/Code/NODE/node_modules/firebase) 的错误(本机) /app-node.js:20:68) at Object.c [as database] (/Users/dd/Desktop/Code/NODE/node_modules/firebase/app-node.js:21:447) at Object. (/Users/dd/Desktop/Code/NODE/Bot.js:24:25) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:394:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:509:3 dd-mac:NODE dd$ (/Users/dd/Desktop/Code/NODE/Bot.js:24:25) 在 Module._compile (module.js:570:32) 在 Object.Module._extensions..js (module.js:579:10 ) 在 Module.load (module.js:487:32) 在 tryModuleLoad (module.js:446:12) 在 Function.Module._load (module.js:438:3) 在 Module.runMain (module.js:604) :10) 在运行时 (bootstrap_node.js:394:7) 在启动时 (bootstrap_node.js:149:9) 在 bootstrap_node.js:509:3 dd-mac:NODE dd$

Could someone please help?有人可以帮忙吗?

You are probably invoking firebase before the app is initialized.您可能在应用程序初始化之前调用了firebase All calls to firebase.firebase.所有调用firebase. must come after .initializeApp();必须.initializeApp();

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

Complete tutorial source link完整的教程链接

Use initializeApp before @NgModule在@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 {}

If you using Dart and Flutter如果你使用 Dart 和 Flutter

  1. add firebase_core dependency to pubspac.ymal.将 firebase_core 依赖项添加到 pubspac.ymal。
  2. go to main.dart转到 main.dart
  3. import 'package:firebase_core/firebase_core.dart';导入'包:firebase_core/firebase_core.dart';

4.add async in main() 4.在main()中添加异步

follow my code按照我的代码

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 ...");
            },
          )
        ],
      ),
    ));
  }
}

My problem was because I added a second parameter:我的问题是因为我添加了第二个参数:

AngularFireModule.initializeApp(firebaseConfig, 'reservas')

if I remove the second parameter it works fine:如果我删除第二个参数它工作正常:

AngularFireModule.initializeApp(firebaseConfig)

If you are using React Native , this error can also happen if you did not configure the native side properly.如果您使用的是React Native ,如果您没有正确配置本机端,也会发生此错误。

Documentation here: https://rnfirebase.io/此处的文档: https://rnfirebase.io/

Android Android

First, download the google-services.json file and place it inside of your project at the following location: /android/app/google-services.json .首先,下载google-services.json文件并将其放在您的项目中的以下位置: /android/app/google-services.json

Then, add the google-services plugin as a dependency inside of your /android/build.gradle然后,将 google-services 插件添加为/android/build.gradle中的依赖项

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

Lastly, execute the plugin by adding the following to your /android/app/build.gradle最后,通过将以下内容添加到您的/android/app/build.gradle来执行插件

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

iOS iOS

First, Add your GoogleService-Info.plist file to the project through xcode.首先,通过 xcode 将您的GoogleService-Info.plist文件添加到项目中。 Make sure it shows up in build phases so you know it's added to the project and not just the folder.确保它显示在构建阶段,以便您知道它已添加到项目中,而不仅仅是文件夹。

Then, open your /ios/{projectName}/AppDelegate.m file, and add the following:然后,打开您的/ios/{projectName}/AppDelegate.m文件,并添加以下内容:

At the top of the file, import the Firebase SDK:在文件顶部,导入 Firebase SDK:

#import <Firebase.h>

Within your existing didFinishLaunchingWithOptions method, add the following to the top of the method:在现有的 didFinishLaunchingWithOptions 方法中,将以下内容添加到方法的顶部:

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

I had a similar issue following Firebase's online guide found here .根据此处找到的 Firebase 在线指南,我遇到了类似的问题。

The section heading "Initialize multiple apps" is misleading as the first example under this heading actually demonstrates how to initialize a single, default app.标题“初始化多个应用程序”的部分具有误导性,因为该标题下的第一个示例实际上演示了如何初始化单个默认应用程序。 Here's said example:举个例子:

// 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();

If you are migrating from the previous 2.x SDK you will have to update the way you access the database as shown above, or you will get the, No Firebase App '[DEFAULT]' error.如果您从之前的 2.x SDK 迁移,则必须更新您访问数据库的方式,如上所示,否则您将收到No Firebase App '[DEFAULT]'错误。

Google has better documentation at the following:谷歌在以下方面有更好的文档:

  1. INITIALIZE: https://firebase.google.com/docs/database/admin/start初始化: https : //firebase.google.com/docs/database/admin/start

  2. SAVE: https://firebase.google.com/docs/database/admin/save-data保存: https : //firebase.google.com/docs/database/admin/save-data

  3. RETRIEVE: https://firebase.google.com/docs/database/admin/retrieve-data检索: https : //firebase.google.com/docs/database/admin/retrieve-data

This may not be best answer but, I had to initialize app with admin and firebase like below.这可能不是最好的答案,但是,我必须像下面这样使用 admin 和 firebase 初始化应用程序。 I use admin for it's own purposes and firebase as well.我将 admin 用于它自己的目的和 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);
            });
    }

Flutter web颤振网络

For me the error occurred when I run my application in "release" mode对我来说,在“发布”模式下运行我的应用程序时发生了错误

flutter run -d chrome --release

and when I deployed the application on the Firebase hosting当我在 Firebase 托管上部署应用程序时

firebase deploy

Solution解决方案

Since I initialized Firebase in the index.html, I had to change the implementation order of firebase and main.dart.js由于我在 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>

If you are starting out a react-native app and seeing this issue, then you have to follow all the instructions listed in firebase (when you setup iOS/android app) or the instructions @ React-native google auth android DEVELOPER_ERROR Code 10 question如果您正在启动react-native应用程序并看到此问题,那么您必须遵循 firebase 中列出的所有说明(当您设置 iOS/android 应用程序时)或@ React-native google auth android DEVELOPER_ERROR Code 10问题的说明

在此处输入图片说明

The answer may already be given somewhere but here is my take to this error which may be thrown for multiple reasons :答案可能已经在某处给出,但这是我对可能由于多种原因引发的错误的看法

  1. Default app is initialized after the other one.默认应用程序在另一个应用程序之后初始化。 Correct way is to initialize the default app first and then the rest.正确的方法是先初始化默认应用程序,然后再初始化其余的应用程序。
  2. firebase.apps.app() is being called before default app initialization. firebase.apps.app()在默认应用初始化之前被调用。 This code is basically returning the default app instance.这段代码基本上是返回默认的应用程序实例。 Since it is not present, hence the error.由于它不存在,因此错误。
  3. Lastly, you are initializing other firebase services like auth, database, firestore, etc before app is initialized.最后,在应用程序初始化之前,您正在初始化其他 firebase 服务,如身份验证、数据库、firestore 等。

Got the same error while working with iOS.使用 iOS 时遇到相同的错误。 Hope you have already installed the Firebase using pods.希望您已经使用 pod 安装了 Firebase。 You need to do the following.您需要执行以下操作。 Open the Xcode and open AppDelegate.m file and import打开 Xcode 并打开 AppDelegate.m 文件并导入

#import "FIRApp.h"

Now call configure method in didFinishLaunchingWithOptions delegate method现在在 didFinishLaunchingWithOptions 委托方法中调用 configure 方法

  [FIRApp configure];

Now run your app.现在运行您的应用程序。 It should work.它应该工作。 Here is doc link这是文档链接

another solution is here.另一个解决方案在这里。

use APP_INITIALIZER使用 APP_INITIALIZER

https://angular.io/api/core/APP_INITIALIZER https://angular.io/api/core/APP_INITIALIZER

export function appInitializer() {
  return () => firebase.initializeApp(firebaseConfig);
}

...
@NgModule({
 ...
 providers: [{
   provide: APP_INITIALIZER,
   useFactory: () => appInitializer
   multi: true
  }]
 })
export class AppModule {}

YOU CALL THIS IN JADE: firebase.initializeApp(config);你在 JADE 中调用它: firebase.initializeApp(config); IN THE BEGIN OF THE FUNC在功能的开始

script.
    function signInWithGoogle() {
        firebase.initializeApp(config);
        var googleAuthProvider = new firebase.auth.GoogleAuthProvider
        firebase.auth().signInWithPopup(googleAuthProvider)
        .then(function (data){
            console.log(data)
        })
        .catch(function(error){
            console.log(error)
        })
    }

I think This Error is Arrived Because of You are using Class Component in Respective React Platform that Doesn't get Proper Configuration.我认为出现此错误是因为您在未获得正确配置的相应 React 平台中使用了类组件。 So You Write Configuration in componentWillMount().所以你在 componentWillMount() 中编写配置。

componetWillMount() {
const config = {
apiKey: “xxxxxxxxxxxxxxxxxxxxxxxx”,
authDomain: “auth-bdcdc.firebaseapp.com 20”,
databaseURL: “https://auth-bdcdc.firebaseio.com 7”,
projectId: “auth-bdcdc”,
storageBucket: “auth-bdcdc.appspot.com 2”,
messagingSenderId: “xxxxxxxxxx”
};

Use Initialize app in the app.module.ts在 app.module.ts 中使用 Initialize app

import { environment } from 'src/environments/environment';
firebase.initializeApp(environment.firebase);

This will clear the error.这将清除错误。
You can use firebase.database() without any errors您可以毫无错误地使用 firebase.database()

This error is because you are trying to use firebase function before it has successfully initialised此错误是因为您在成功初始化之前尝试使用 firebase 函数

Fix:修复:

Place the function you want to call inside setInterval block such that the function is called only once the app has been initialised:将您要调用的函数放在 setInterval 块中,以便仅在应用程序初始化后调用该函数:

 let isFirebaseAppDefined = false;
    setInterval(() => {
      if (!isFirebaseAppDefined) {
        if (firebase.app()) {

          // Function that needs to run after the initialisation comes here
          // Example re-captcha verifier or other auth function

          isFirebaseAppDefined = true;
        }
      }
    }, 100);

If you are on react native and developing for IOS then I think you forgot the linking steps of firebase module.如果您正在使用 React Native 并为 IOS 开发,那么我认为您忘记了 firebase 模块的链接步骤。

follow the below steps..!请按照以下步骤操作..!

open your /ios/{projectName}/AppDelegate.m file, and add the following:打开您的/ios/{projectName}/AppDelegate.m文件,并添加以下内容:

At the top of the file, import the Firebase SDK:在文件顶部,导入 Firebase SDK:

#import <Firebase.h>

Within your existing didFinishLaunchingWithOptions method, add the following to the top of the method:在您现有的didFinishLaunchingWithOptions方法中,将以下内容添加到该方法的顶部:

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

I had the same issue.我遇到过同样的问题。 When I tried adding my flutter web app to firebase I took the Script tags google gave me in the setup process and pasted them into my index.html.当我尝试将我的 flutter web 应用程序添加到 firebase 时,我将谷歌在设置过程中给我的脚本标签粘贴到我的 index.html 中。 That didn't work for me even AFTER I modified my main.dart with the following lines in the main method:即使在我在 main 方法中使用以下几行修改了 main.dart 之后,这对我也不起作用:

WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());

Using the Script in the format posted here I got it working: https://firebase.flutter.dev/docs/installation/web使用此处发布的格式的脚本我让它工作了: https : //firebase.flutter.dev/docs/installation/web

If there are other people having the same issue and blindly copying the Script Tags Google gives you in the Firebase Setup.... this helped me.如果还有其他人遇到同样的问题并盲目复制 Google 在 Firebase 设置中为您提供的脚本标签......这对我有帮助。 Just get it into the format posted by FlutterFire.只需将其转换为 FlutterFire 发布的格式即可。

I got this error in ios when I updated the React Native version, add this instruction in method: didFinishLaunchingWithOptions from file: ios/{AppName}/AppDelegate.m当我更新 React Native 版本时,我在 ios 中遇到了这个错误,在方法中添加这个指令: didFinishLaunchingWithOptions from file: ios/{AppName}/AppDelegate.m

   if ([FIRApp defaultApp] == nil) {
     [FIRApp configure];
   }

It should look like this:它应该如下所示: 在此处输入图像描述

In my case the solution was remplace this在我的情况下,解决方案是替换这个

const firebaseConfig = {
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        projectId: "",
        storageBucket: "",
        messagingSenderId: "",
        appId: "",
        measurementId: ""
    };
const app = initializeApp(firebaseConfig);

to this.....对此……

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.8/firebase-app.js";
firebase.initializeApp({
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        projectId: "",
        storageBucket: "",
        messagingSenderId: "",
        appId: "",
        measurementId: ""
    });

I hope it works for you:)我希望这个对你有用:)

in my case i was using就我而言,我正在使用

getAuth()
getFirestore()

with out passing the app instead use it like不通过应用程序而是像使用它一样使用它

const app = initializeApp(config);
const auth = getAuth(app);
const db = getFirestore(app);

Step 1:步骤1:

Using npm使用npm

npm install --save @react-native-firebase/app npm 安装 --save @react-native-firebase/app

Using Yarn使用纱线

yarn add @react-native-firebase/app纱线添加@react-native-firebase/app

step 2: Generating Android credentials in https://console.firebase.google.com/ The "Android package name" must match your local project's package name which can be found inside of the manifest tag within the /android/app/src/main/AndroidManifest.xml file within your project. step 2: Generating Android credentials in https://console.firebase.google.com/ The "Android package name" must match your local project's package name which can be found inside of the manifest tag within the /android/app/src/项目中的 main/AndroidManifest.xml 文件。

Download the google-services.json file and place it inside of your project at the following location: /android/app/google-services.json.下载 google-services.json 文件并将其放在您的项目中的以下位置:/android/app/google-services.json。

step3: and then add the google-services plugin as a dependency inside of your /android/build.gradle file: classpath 'com.google.gms:google-services:4.3.13'第 3 步:然后将 google-services 插件添加为 /android/build.gradle 文件中的依赖项:classpath 'com.google.gms:google-services:4.3.13'

Lastly, execute the plugin by adding the following to your /android/app/build.gradle file: apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' // <- Add this line最后,通过将以下内容添加到 /android/app/build.gradle 文件来执行插件: apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' // <- Add这条线

That's all....就这样....

I found the solution!我找到了解决方案!

Follow these steps:请按照以下步骤操作:

Flutter Firebase and Android issue - unable to Initialise. Flutter Firebase 和 Android 问题 - 无法初始化。 Cannot find google-services.json with latest migration instructions executed 无法找到执行了最新迁移指令的 google-services.json

After that, execute:之后,执行:

flutter build apk --debug
flutter build apk --profile
flutter build apk --release

and then, run app!然后,运行应用程序! it works for me!它对我有用!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter Web - No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app) - Flutter Web - No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app) 没有 Firebase 应用程序“[DEFAULT]”已创建 - 调用 Firebase App.initializeApp() - Firebase 存储 - No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() - Firebase Storage 如何解决 Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app) - How to solve Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app) FirebaseError: Firebase: 否 Firebase App '[DEFAULT]' 已创建 - 调用 Firebase App.initializeApp() {颤动网络} - FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app). {Flutter web} React Native 错误:没有创建 Firebase App '[DEFAULT]' - 调用 firebase.initializeApp() - React Native Error: No Firebase App '[DEFAULT]' has been created - call firebase.initializeApp() 没有创建 Firebase App '[DEFAULT]' - 在 Flutter 和 Firebase 调用 Firebase.initializeApp() - No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() in Flutter and Firebase 没有 Firebase 应用程序“[DEFAULT]”已创建 - 在 Flutter 中调用 Firebase.initializeApp() - No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() in Flutter 初始化 Firebase 后出现“无默认应用”异常 - 'no default app' exception after Firebase has been initialized 没有 Firebase 应用程序“[默认]”错误,但 firebase 已经初始化 - No Firebase App '[Default]' error but firebase is already initialized Google Cloud Functions Firebase 错误 默认的 Firebase 应用已经存在 - Google Cloud Functions Firebase Error The default Firebase app already exists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM