programing

오류: Firebase App '[DEFAULT]'이(가) 생성되지 않았습니다. Firebase App.initializeApp() 호출

linuxpc 2023. 7. 10. 22:08
반응형

오류: Firebase App '[DEFAULT]'이(가) 생성되지 않았습니다. Firebase App.initializeApp() 호출

파이어베이스 데이터베이스는 최대 두 개의 앱으로 연결되어 있는데, 하나는 iOS 앱이고 다른 하나는 데이터베이스에 데이터를 설정하는 기본 알고리즘인 node.js로 코딩된 웹 앱입니다.알고리즘을 실행할 때마다 저는 직면하게 됩니다.

오류: Firebase App '[DEFAULT]'이(가) 생성되지 않았습니다. 오류(네이티브)의 R(/Users/dd/Desktop/Code/NODE/node_modules/app-node.js:22:335)에서 Firebase App.initializeApp(. . . . . . . . . . . . . . . .)을(/Desktop/Desktop/NODEnode/NODEnode/NODEmodules)에 호출합니다.js:21:447).(/Users/dd/Desktop/Code/NODE/Bot.js:24:25)가 모듈에 있습니다._compile(module.js:570:32)이 Object에 있습니다.모듈._확장..module.load(module.js:579:10)에서 function에서 tryModuleLoad(module.js:446:12)로 설정됩니다.시작 시(bootstrap_node.js:149:9) 실행 시(bootstrap_node.js:149:9) Module.runMain(module.js:438:3)의 Module.load(module.js:604:10)노드 dd$

누가 좀 도와주시겠어요?

" 아호출중것다니입일"를 호출하고 입니다.firebase앱이 초기화되기 전에.는 대든통상모화대상.firebase다음에 와야 합니다. .initializeApp();

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

각도를 사용하는 경우 여기에 해결책이 있습니다.

전체 자습서 원본 링크

@NgModule 이전에 초기화 앱 사용

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

React Native를 사용하는 경우 네이티브 측을 제대로 구성하지 않은 경우에도 이 오류가 발생할 수 있습니다.

여기에 있는 설명서: https://rnfirebase.io/

안드로이드

먼다운합다니를 합니다.google-services.json의 다음합니다./android/app/google-services.json.

다음 을 그런다 Google 합니다./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

첫 번째로, 당신의 것을(를)GoogleService-Info.plistxcode를 통해 프로젝트에 파일을 보냅니다.폴더뿐만 아니라 프로젝트에 추가되었음을 알 수 있도록 빌드 단계에 표시해야 합니다.

다음, 여러분의 런다음, 을엽다를 ./ios/{projectName}/AppDelegate.m파일을 저장하고 다음을 추가합니다.

파일의 맨 위에서 Firebase SDK를 가져옵니다.

#import <Firebase.h>

기존 didFinishLaunchingWithOptions 메서드에서 메서드의 맨 위에 다음을 추가합니다.

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

다트와 플래터를 사용하는 경우

  1. pubspac.ymal에 firebase_core 종속성을 추가합니다.
  2. 메인으로 이동합니다.
  3. 'package:firebase_core/firebase_core.package' 가져오기;

4.메인에 비동기 추가 »

내 규칙을 따르라.

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

여기서 발견된 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. " 2.x SDK"라는 메시지가 됩니다. 그렇지 않으면 다음과 같은 정보를 얻을 수 있습니다.No Firebase App '[DEFAULT]'message

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

두 번째 매개 변수를 추가했기 때문에 문제가 발생했습니다.

AngularFireModule.initializeApp(firebaseConfig, 'reservas')

두 번째 매개 변수를 제거하면 정상적으로 작동합니다.

AngularFireModule.initializeApp(firebaseConfig)

이것이 최선의 답변은 아닐 수 있지만 아래와 같이 관리자와 파이어베이스로 앱을 초기화해야 했습니다.저는 관리자 자신의 목적과 소방 기지를 위해서도 사용합니다.

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 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. 기본 앱은 다른 앱 다음에 초기화됩니다.올바른 방법은 기본 앱을 먼저 초기화한 다음 나머지를 초기화하는 것입니다.
  2. firebase.apps.app()기본 앱 초기화 전에 호출됩니다.이 코드는 기본적으로 기본 앱 인스턴스를 반환합니다.존재하지 않기 때문에 오류가 발생합니다.
  3. 마지막으로, 앱이 초기화되기 전에 인증, 데이터베이스, 파이어스토어 등과 같은 다른 파이어베이스 서비스를 초기화하는 것입니다.

만약 당신이 IOS를 위해 리액트 네이티브로 개발하고 있다면, 당신은 파이어베이스 모듈의 연결 단계를 잊어버렸다고 생각합니다.

다음 단계를 따릅니다...!

신의것을 /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 --- /\
  // ...
}

반응 네이티브 앱을 시작하고 이 문제가 발생하는 경우 파이어베이스에 나열된 모든 지침(iOS/안드로이드 앱을 설정할 때) 또는 @ 반응 네이티브 구글 인증 안드로이드 개발자_ERROR 코드 10 질문을 따라야 합니다.

enter image description here

iOS로 작업하는 동안 동일한 오류가 발생했습니다.포드를 사용하여 Firebase를 이미 설치했으면 합니다.다음을 수행해야 합니다.Xcode를 열고 AppDelegate.m 파일을 열고 가져옵니다.

#import "FIRApp.h"

이제 didFinishLaunchingWithOptions 대리 메서드에서 구성 메서드를 호출합니다.

  [FIRApp configure];

이제 앱을 실행합니다.그건 작동할 거야.문서 링크입니다.

당신은 이것을 옥으로 부릅니다: 화력 기지.앱 초기화(config); 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)
        })
    }

이 오류는 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);

다른 해결책이 여기 있습니다.

APP_INITIAZER 사용

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

할 때 이 메소드에 하십시오. 방법에 다음 지침을 추가하십시오.didFinishLaunchingWithOptions 파에서:ios/{AppName}/AppDelegate.m

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

다음과 같이 표시되어야 합니다.

app.module.ts에서 app 초기화 사용

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

이렇게 하면 오류가 해결됩니다.
를 사용할 수 .

저도 같은 문제가 있었습니다.파이어베이스에 플래터 웹 앱을 추가하려고 할 때 구글이 설정 과정에서 준 스크립트 태그를 가져다가 index.html에 붙여넣었습니다.main.dart를 메인 메소드에서 다음 행으로 수정한 후에도 작동하지 않았습니다.

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

여기에 게시된 형식의 스크립트를 사용하여 작동했습니다. https://firebase.flutter.dev/docs/installation/web

다른 사람들이 동일한 문제를 가지고 있고 구글이 파이어베이스 설정에서 제공하는 스크립트 태그를 맹목적으로 복사하는 경우...이것이 저를 도왔습니다.Floatter Fire가 게시한 형식으로 가져오면 됩니다.

제 경우에는 사용하고 있었습니다.

getAuth()
getFirestore()

앱을 통과하지 않고 대신 다음과 같이 사용합니다.

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

1단계:

npm 사용

npm 설치 --save @sessage-native-firebase/app

실 사용

실 추가 @실버-네이티브-파이어베이스/앱

2단계: https://console.firebase.google.com/ 에서 Android 자격 증명 생성 "Android 패키지 이름"은 프로젝트 내의 /Android/app/src/main/AndroidManifest.xml 파일 내의 매니페스트 태그 내부에 있는 로컬 프로젝트의 패키지 이름과 일치해야 합니다.

Google-services.json 파일을 다운로드하여 프로젝트 내부의 /android/app/google-services.json 위치에 배치합니다.

3단계: 그런 다음 /build/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' // <- 이 줄 추가

그게 다야...

사용 방법: https://github.com/abhi3700/My_Learning_Databases/tree/main/Firebase#initialize-firestore

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

const serviceAccount = require("../../../helper/serviceAccountKey.json");

let db = null;

// initialize firebase
if (!fs.apps.length) {
  fs.initializeApp({
    credential: fs.credential.cert(serviceAccount),
    // name: "zippy-mvp2",
  });

  db = fs.firestore();

  // allow undefined values.
  db.settings({
    ignoreUndefinedProperties: true,
  });
} else {
  db = fs.app().firestore();
}

이 오류는 올바른 구성을 얻지 못하는 각 대응 플랫폼에서 클래스 구성 요소를 사용하고 있기 때문에 발생한 것으로 생각됩니다.따라서 WillMount() 구성 요소의 쓰기 구성입니다.

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”
};

저의 경우 솔루션이 이를 대체했습니다.

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: ""
    });

당신에게 효과가 있기를 바랍니다 :)

해결책을 찾았어요!

다음 단계를 수행합니다.

Floating Firebase 및 Android 문제 - 초기화할 수 없습니다.최신 마이그레이션 지침이 실행된 Google-services.json을 찾을 수 없습니다.

그런 다음 다음을 실행합니다.

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

그리고 나서, 앱을 실행하세요! 그것은 나에게 효과가 있습니다!

언급URL : https://stackoverflow.com/questions/40563140/error-no-firebase-app-default-has-been-created-call-firebase-app-initiali

반응형