繁体   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. 每当我运行算法时,我都会遇到-

错误:没有 Firebase 应用程序“[DEFAULT]”已创建 - 调用 Firebase App.initializeApp()。 在 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) 在 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$

有人可以帮忙吗?

您可能在应用程序初始化之前调用了firebase firebase.所有调用firebase. 必须.initializeApp();

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

完整的教程链接

在@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 {}

如果你使用 Dart 和 Flutter

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

4.在main()中添加异步

按照我的代码

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

我的问题是因为我添加了第二个参数:

AngularFireModule.initializeApp(firebaseConfig, 'reservas')

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

AngularFireModule.initializeApp(firebaseConfig)

如果您使用的是React Native ,如果您没有正确配置本机端,也会发生此错误。

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

Android

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

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

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 --- /\
  // ...
}

根据此处找到的 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]'错误。

谷歌在以下方面有更好的文档:

  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

这可能不是最好的答案,但是,我必须像下面这样使用 admin 和 firebase 初始化应用程序。 我将 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 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>

如果您正在启动react-native应用程序并看到此问题,那么您必须遵循 firebase 中列出的所有说明(当您设置 iOS/android 应用程序时)或@ React-native google auth android DEVELOPER_ERROR Code 10问题的说明

在此处输入图片说明

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

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

使用 iOS 时遇到相同的错误。 希望您已经使用 pod 安装了 Firebase。 您需要执行以下操作。 打开 Xcode 并打开 AppDelegate.m 文件并导入

#import "FIRApp.h"

现在在 didFinishLaunchingWithOptions 委托方法中调用 configure 方法

  [FIRApp configure];

现在运行您的应用程序。 它应该工作。 这是文档链接

另一个解决方案在这里。

使用 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 {}

你在 JADE 中调用它: firebase.initializeApp(config); 在功能的开始

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)
        })
    }

我认为出现此错误是因为您在未获得正确配置的相应 React 平台中使用了类组件。 所以你在 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”
};

在 app.module.ts 中使用 Initialize app

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

这将清除错误。
您可以毫无错误地使用 firebase.database()

此错误是因为您在成功初始化之前尝试使用 firebase 函数

修复:

将您要调用的函数放在 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);

如果您正在使用 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 --- /\
  // ...
}

我遇到过同样的问题。 当我尝试将我的 flutter web 应用程序添加到 firebase 时,我将谷歌在设置过程中给我的脚本标签粘贴到我的 index.html 中。 即使在我在 main 方法中使用以下几行修改了 main.dart 之后,这对我也不起作用:

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

使用此处发布的格式的脚本我让它工作了: https : //firebase.flutter.dev/docs/installation/web

如果还有其他人遇到同样的问题并盲目复制 Google 在 Firebase 设置中为您提供的脚本标签......这对我有帮助。 只需将其转换为 FlutterFire 发布的格式即可。

当我更新 React Native 版本时,我在 ios 中遇到了这个错误,在方法中添加这个指令: didFinishLaunchingWithOptions from file: ios/{AppName}/AppDelegate.m

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

它应该如下所示: 在此处输入图像描述

在我的情况下,解决方案是替换这个

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

对此……

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

我希望这个对你有用:)

就我而言,我正在使用

getAuth()
getFirestore()

不通过应用程序而是像使用它一样使用它

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

步骤1:

使用npm

npm 安装 --save @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 文件。

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

第 3 步:然后将 google-services 插件添加为 /android/build.gradle 文件中的依赖项:classpath 'com.google.gms:google-services:4.3.13'

最后,通过将以下内容添加到 /android/app/build.gradle 文件来执行插件: apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' // <- Add这条线

就这样....

我找到了解决方案!

请按照以下步骤操作:

Flutter Firebase 和 Android 问题 - 无法初始化。 无法找到执行了最新迁移指令的 google-services.json

之后,执行:

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

然后,运行应用程序! 它对我有用!

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM