Firebase模拟器向本地FireStore的请求失败

问题描述

Firebase模拟器向本地FireStore的请求失败

你好

我正在尝试设置Firebase仿真器,而我的应用仍在连接到Firebase(web)。当我执行db.collection(“ users”)。add()时,我看到https://console.firebase.google.com上的条目不在http:// localhost:4000 / firestore上(主机端口为8080,查看器端口为4000)

这是我到目前为止所做的:

  1. Firebase仿真器:start返回“所有仿真器已准备就绪!”

  2. Firebase.json看起来不错(端口看起来不错)

"emulators": {
    "functions": {
      "port": 5001
    },"firestore": {
      "port": 8080
    },"database": {
      "port": 9000
    },"hosting": {
      "port": 5000
    },"pubsub": {
      "port": 8085
    },"ui": {
      "enabled": true
}
  1. 在初始化应用程序之前,我将databaseURL更改为我的本地Firestore。 请注意,在视频“ 15分钟内完成本地Firebase模拟器UI”(https://www.youtube.com/watch?v=pkgvFNPdiEs 5:19)中,David East用“ config = {databaseURL:'...'}”替换了整个配置对象,但返回了错误:“ firebase.initializeApp中未提供未捕获的FirebaseError:“ projectId””,如果我添加了值键projectId,它将返回丢失的其他错误
if (location.hostname === "localhost") {
  config.databaseURL = "http://localhost:8080?ns=project_name";
}

firebase.initializeApp(config);
  1. 使用良好项目(Firebase Firestore works with real database but not emulator)的Firebase
firebase use project_name
  1. 我还创建了Google Cloud Platform私钥...以防万一。

我认为我的问题可能出在步骤3中,但是我找不到解决方法。你有什么主意吗您如何使它正常工作?

谢谢!

解决方法

您已到达目的地,但我认为自视频制作以来,连接到本地数据库模拟器的方法已经改变。

我成功使用以下方法连接到本地数据库仿真器:

if (!firebase.apps.length) {
  let config = {
    apiKey: "-------------------",authDomain: "--------------",databaseURL: "------------------",projectId: "----------------",storageBucket: "---------------------",messagingSenderId: "--------------",appId: "----------------------",measurementId: "-----------------"
  };

  firebase.initializeApp(config);

  if (location.hostname === "localhost") {
    var db = firebase.firestore();
    db.settings({
      host: "localhost:8080",ssl: false
    });
  }
}

用于在线连接的原始配置保留不变,但是如果location.hostname ===“ localhost”,则将进行适当的更改。

firebase.initializeApp(config)必须位于可检测应用程序本地运行的if语句之上。

幸运的是,该应用程序继续使用在线身份验证,并且数据库和功能连接是本地的。

最新文档在这里:https://firebase.google.com/docs/emulator-suite/connect_and_prototype