简体   繁体   English

使用 firebase 的网络应用程序的正确文件结构

[英]Correct file structure for a web-app that uses firebase

I am trying (and failing) to implement Firebase on my existing web-app.我正在尝试(但失败了)在我现有的网络应用程序上实施 Firebase。 I keep getting the error: Uncaught FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created我不断收到错误消息: Uncaught FirebaseError: Firebase: No Firebase App '[DEFAULT]' has created

I believe that the problem resides with my file structure.我相信问题出在我的文件结构上。 In /MY_APP, I have the files I created and wrote for my app.在 /MY_APP 中,我有我为我的应用程序创建和编写的文件。 In inner directories, there are the firebase automatically created.html and.js files.在内部目录中,有自动创建的 firebase.html 和.js 文件。

|- /MY_APP
    |- index.html <-- contains my web-app
    |- code.js
    |- styles.css
    |- /src
        |- index.js <-- contains initializeApp Firebase config (apiKey, ...)
        |- /dist
            |- firebase.json
            |- .firebaserc.json
            |- /ManresaSegura
                |- index.html <-- example Firebase app (created automatically)
                |- app.js
 

Desired result: Continue using my original "index.html" file (the one found inside /MY_APP directory)期望的结果:继续使用我原来的“index.html”文件(在 /MY_APP 目录中找到的那个)

firebase.json (as created by firebase) : firebase.json(由 firebase 创建)

    {
  "hosting": {
    "public": "ManresaSegura",  
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  },
  "database": {
    "rules": "database.rules.json"
  }
}

I tried changing the following (which didn't work):我尝试更改以下内容(无效):

"public": "../../../MY_APP"
...
"destination": "../../index.html

*EDIT: Additional code, as asked for: *编辑:附加代码,要求:

index.js (Firebase initialization) index.js (Firebase 初始化)

import {initializeApp} from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js';
import { getAuth, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js';
    
    //import {initializeApp} from 'firebase/app';
    //import { getAuth, onAuthStateChanged } from 'firebase/auth';
    
    
    const firebaseApp = initializeApp({
        apiKey: "XXXXXX",
        authDomain: "XXXXXXX",
        projectId: "XXXXXXXXXXXX",
        storageBucket: "XXXXXXXXXXX",
        messagingSenderId: "XXXXXXXXX",
        appId: "XXXXXXXXXXXXXXX",
        measurementId: "XXXXXXXXX"
        
    });
    
    
    const auth = getAuth(firebaseApp);

app.js (db is defined, which is then instanced in index.html) app.js (定义了db,然后在index.html中实例化)

document.addEventListener("DOMContentLoaded", event => {

    const app = firebase.app();
    
    const db = firebase.firestore();
    
    const myPost = db.collection('posts').doc('firstpost');

 });

index.html (original) index.html(原件)

<html>
    <head>

        ...
        <script type="text/javascript" src="code.js"></script>

        <!-- Firebase -->

        <script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
        <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>  
        <script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js"></script> 

        

    <script type="module" defer src="src/index.js?useEmulator=true"></script>
        <!-- update the version number as needed -->
    <script defer src="/__/../node_modules/firebase/firebase-app-compat.js"></script>
    <!-- include only the Firebase features as you need -->
    <script defer src="/__/../node_modules/firebase/firebase-auth-compat.js"></script>
    <script defer src="/__/../node_modules/firebase/firebase-database-compat.js"></script>
    <script defer src="/__/../node_modules/firebase/firebase-firestore-compat.js"></script>
    <script defer src="/__/../node_modules/firebase/firebase-functions-compat.js"></script>
    <script defer src="/__/../node_modules/firebase/firebase-messaging-compat.js"></script>
    <script defer src="/__/../node_modules/firebase/firebase-storage-compat.js"></script>
    <script defer src="/__/../node_modules/firebase/firebase-analytics-compat.js"></script>
    <script defer src="/__/../node_modules/firebase/firebase-remote-config-compat.js"></script>
    <script defer src="/__/../node_modules/firebase/firebase-performance-compat.js"></script>
    <!-- 
      initialize the SDK after all desired features are loaded, set useEmulator to false
      to avoid connecting the SDK to running emulators.
        -->
    

    </head>
    
    <body id="caixaCos">
       <script src="src/dist/ManresaSegura/app.js">  
            
        </script>

        ...
        <!-- Input type data I want to send to firebase database -->
        <input class="input-time" type="time" id="appt" name="appt"
        min="09:00" max="18:00" required>
        

        <button id="boto-zonaInsegura" type="submit">
                Enviar
        </button>

                <script type="text/javascript">
                
                document.getElementById("boto-zonaInsegura").onclick = function () {
                    const hora = document.querySelector(".input-time");  
                    db.collection("contact-form")
                    .doc()
                    .set({
                        Hora: hora,
                    })
                };

            </script> 

        </div>
...
        
    </body>
</html>

As firebase isn't correctly implemented, I get the error Uncaught ReferenceError: db is not defined由于 firebase 没有正确实现,我收到错误Uncaught ReferenceError: db is not defined

Question: What am I doing wrong in the firebase.json file, why doesn't it access the my app?问题:我在 firebase.json 文件中做错了什么,为什么它不能访问我的应用程序? Is the only neat way of proceeding to copy all my code into the index.html created by firebase (in the /ManresaSegura directory)?将我的所有代码复制到由firebase (在 /ManresaSegura 目录中)创建的 index.html 中是唯一巧妙的方法吗?

Thanks a lot.非常感谢。 I am a novice in Firebase and not very skilled in js.我是Firebase的新手,对js不是很熟练。

That last code snippet (index.html) in your question doesn't define db anywhere, but does then try to use db to access Firestore, which leads to the error message.您问题中的最后一个代码片段 (index.html) 没有在任何地方定义db随后尝试使用db访问 Firestore,这导致了错误消息。

If you want to use Firestore in your index.html too, you'll need to ensure that you initialize Firebase and your db variable are initialized before that block executes.如果你也想在你的 index.html 中使用 Firestore,你需要确保你初始化 Firebase 并且你的db变量在该块执行之前被初始化。

It's actually fairly uncommon to have script blocks in your index.html when you also have dedicated files like code.js and app.js, so I recommend moving all JavaScript code into those files - at which point they'll be executed after the initialization has completed.当你还有像 code.js 和 app.js 这样的专用文件时,在你的 index.html 中使用脚本块实际上是相当罕见的,所以我建议将所有 JavaScript 代码移动到这些文件中 - 此时它们将在初始化后执行已经完成。

db is initialised in an event's callback. db在事件的回调中初始化。 Which means it isn't available outside the scope of that callback.这意味着它在该回调的 scope 之外不可用。 What you want to do is this你想做的是这个

let app;
let db;

document.addEventListener("DOMContentLoaded", event => {

    app = firebase.app();

    db = firebase.firestore();

    const myPost = db.collection('posts').doc('firstpost');
});

暂无
暂无

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

相关问题 Azure Active Directory in .NET Core 2.2 Web-App | 签名无效/未找到签名密钥 - Azure Active Directory in .NET Core 2.2 Web-App | the signature is invalid / signature key was not found 如何将图像文件上传到Firebase存储并在Flutter web app中显示 - How to upload an image file to Firebase Storage and show it in the Flutter web app 如何构建多区域 firebase 应用程序? - How to structure a multi-region firebase app? 构建一个使用 firebase_auth 的 flutter 应用程序,它在手机上运行良好,但在我在 web 上运行时出错,说 http_parser 路径丢失 - Building a flutter app that uses firebase_auth which runs fine on phone but gives error while i run on web, says http_parser path missing 使用相同的 Firebase 应用程序与 Web 和移动应用程序 - Using Same Firebase App With Web and Mobile App 如何配置 Spring Boot 以使用 AWS Cognito (OAuth2/OIDC) 对 Web 应用程序用户和 REST 客户端进行身份验证 - How to configure Spring Boot to authenticate Web-app users and REST clients using AWS Cognito (OAuth2/OIDC) Firebase AppCheck web 应用程序无法在生产模式下工作 - Firebase AppCheck web app not working in production mode 如何在Firebase上为web设置应用版本 - How to set app version on Firebase for web Flutter web - 上传图片文件到Firebase存储 - Flutter web - Upload Image File to Firebase Storage Firebase Tensorflow Lite 分类模型未在 Swift 应用程序中提供正确的输出 - Firebase Tensorflow Lite Classification Model Not Giving Correct Output in Swift App
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM