【问题标题】:Uncaught ReferenceError: db is not defined未捕获的 ReferenceError:未定义 db
【发布时间】:2021-10-30 18:28:39
【问题描述】:

我是 Firestore 的新手,我正在尝试在 app.js 中使用 db,但是当我运行 html 文件时,我在控制台上收到此错误(未捕获的 ReferenceError:db is not defined)。请问我该如何解决这个问题?

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div>
        <h1>Cloud cafe</h1>
        <div class="content">
            <form id="add-cafe-form"></form>
            <ul id="cafe-list"></ul>
        </div>
    </div>
    
    <script type="module">

      // Import the functions you need from the SDKs you need
      import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
      import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-analytics.js";
      import { getFirestore} from "https://www.gstatic.com/firebasejs/9.0.1/firebase-firestore.js";
      // TODO: Add SDKs for Firebase products that you want to use
      // https://firebase.google.com/docs/web/setup#available-libraries

      // Your web app's Firebase configuration
      // For Firebase JS SDK v7.20.0 and later, measurementId is optional
      const firebaseConfig = {
        apiKey: "AIzaSyA_iQKn0dazcTipquleNaF0df32KdWKia4",
        authDomain: "ninja-flutter-tut.firebaseapp.com",
        projectId: "ninja-flutter-tut",
        storageBucket: "ninja-flutter-tut.appspot.com",
        messagingSenderId: "876805702468",
        appId: "1:876805702468:web:cd2cc55cc394f94726cd11",
        measurementId: "G-9HDMHXT2PY"
      };

      // Initialize Firebase
      const app = initializeApp(firebaseConfig);
      const analytics = getAnalytics(app);
      const db = getFirestore(app);
    </script>
    <script src="app.js"></script>
</body>
</html>

下面是 app.js 的代码

// getting data
db.collection('cafes').get().then(snapshot => {
    console.log("test");
});

【问题讨论】:

    标签: javascript html google-cloud-firestore


    【解决方案1】:

    最可能的原因是您的 app.js 文件在您定义 db 变量之前被执行。您可能希望在 app.js 脚本中添加一个 defer 语句,因为您在上面的脚本中定义了 db 变量,如下所示:

    <script src="app.js" defer></script>
    

    最好只在 app.js 文件中包含第一个脚本内容,这样您就没有像这样的两个单独的脚本文件: app.js:

      // Import the functions you need from the SDKs you need
      import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
      import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-analytics.js";
      import { getFirestore} from "https://www.gstatic.com/firebasejs/9.0.1/firebase-firestore.js";
      // TODO: Add SDKs for Firebase products that you want to use
      // https://firebase.google.com/docs/web/setup#available-libraries
    
      // Your web app's Firebase configuration
      // For Firebase JS SDK v7.20.0 and later, measurementId is optional
      const firebaseConfig = {
        apiKey: "AIzaSyA_iQKn0dazcTipquleNaF0df32KdWKia4",
        authDomain: "ninja-flutter-tut.firebaseapp.com",
        projectId: "ninja-flutter-tut",
        storageBucket: "ninja-flutter-tut.appspot.com",
        messagingSenderId: "876805702468",
        appId: "1:876805702468:web:cd2cc55cc394f94726cd11",
        measurementId: "G-9HDMHXT2PY"
      };
    
      // Initialize Firebase
      const app = initializeApp(firebaseConfig);
      const analytics = getAnalytics(app);
      const db = getFirestore();
    
      // getting data
    db.collection('cafes').get().then(snapshot => {
        console.log("test");
    });
    

    【讨论】:

    • 我加了defer后问题依然存在。我也试过按照你说的组合脚本,但它显示了这个错误(Uncaught SyntaxError: Cannot use import statement outside a module)。
    • 您是否尝试将代码合并到 app.js 文件中?
    • 是的,我以前试过。出现这个错误(Uncaught SyntaxError: Cannot use import statement outside a module)
    • 在初始化 Firestore 时尝试删除“应用程序”:const db = getFirestore();
    • 很高兴听到您设法解决了这个问题!也许只是发布你的答案,以防其他人在同样的事情上挣扎;)
    【解决方案2】:

    您正在使用版本 9 的新 SDK,但为 SDK 版本 8 编写代码。尝试检查 thisthis。只是不要忘记选择正确的版本:

    采集示例代码:

    import { collection, getDocs } from "firebase/firestore"; 
    
    const querySnapshot = await getDocs(collection(db, "users"));
    querySnapshot.forEach((doc) => {
      console.log(`${doc.id} => ${doc.data()}`);
    });
    

    【讨论】:

    • 我检查了链接,但没有找到需要更改的部分,因为声明 db 变量的方式与我的代码和版本 9 (firebase.google.com/docs/web/…) 相同。跨度>
    • 我的意思更多的是你如何获得收藏。该错误可能来自collection中缺少的db
    • 我把版本从v9.0.1改成v8.10.0后问题解决了。无论如何,感谢您的帮助!
    【解决方案3】:

    以下是我的解决方案:

    // app.js
    
    // getting data
    db.collection('cafes').get().then((snapshot) => {
        console.log('test')
    });
    /* style.css */
    
    body{
        background: #eab0dc;
        font-family: ubuntu;
    }
    
    h1{
        color: #fff;
        font-size: 64px;
        letter-spacing: 2px;
        margin-top: 80px;
        text-align: center;
    }
    
    .content{
        background: #fff;
        max-width: 960px;
        margin: 30px auto;
        padding:  20px 30px;
        border-radius: 10px 120px 10px 10px;
        box-shadow: 1px 3px 5px rgba(0,0,0,0.1)
    }
    
    ul{
        list-style-type: none;
        padding: 0;
    }
    
    li{
        padding: 20px;
        background: #f6f6f6;
        font-size: 20px;
        color: #555;
        position: relative;
        border-bottom: 1px solid #e6e6e6;
        height: 46px;
    }
    
    li:nth-child(even){
        padding: 20px;
        background: #f2f2f2;
    }
    
    li span{
        display: block;
    }
    
    li span:nth-child(2){
        font-size: 16px;
        margin-top: 6px;
        color: #999;
    }
    
    li div{
        position: absolute;
        top: 0;
        right: 0px;
        background: rgba(255,255,255,0.6);
        width: 40px;
        text-align: center;
        padding: 10px 0;
        font-weight:  bold;
        cursor:  pointer;
    }
    
    form input{
        float: left;
        width: 38%;
        margin: 0;
        border: 0;
        border-bottom: 1px solid #eee;
        margin: 0 1%;
        padding: 10px;
        display: block;
        box-sizing: border-box;
        font-size: 18px;
    }
    
    form input:focus{
        outline: none;
        border-bottom: 3px solid #88236f;
        padding-bottom: 8px;
        transition: all ease 0.2s;
    }
    
    form:after{
        content: '';
        clear: both;
        display: block;
    }
    
    button{
        border: 0;
        background: #fff;
        border-radius: 10px;
        padding: 13px;
        width: 14%;
        box-shadow: -1px 0px 1px rgba(0,0,0,0.1);
        font-weight: bold;
        font-family: ubuntu;
        letter-spacing: 1px;
        color: #999;
    }
    <html>
        <head>
            <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
            <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-firestore.js"></script>
            <link rel="stylesheet" href="style.css">
        </head>
        <body>
            <h1>Cloud Cafe</h1>
            <div class="content">
                <form id="add-cafe-form"></form>
                <ul id="cafe-list"></ul>
            </div>
            <script>
                // For Firebase JS SDK v7.20.0 and later, measurementId is optional
                const firebaseConfig = {
                  apiKey: "AIzaSyA_iQKn0dazcTipquleNaF0df32KdWKia4",
                  authDomain: "ninja-flutter-tut.firebaseapp.com",
                  projectId: "ninja-flutter-tut",
                  storageBucket: "ninja-flutter-tut.appspot.com",
                  messagingSenderId: "876805702468",
                  appId: "1:876805702468:web:cd2cc55cc394f94726cd11",
                  measurementId: "G-9HDMHXT2PY"
                };
                firebase.initializeApp(firebaseConfig);
                const db = firebase.firestore();
            </script>
            <script src="app.js"></script>
        </body>
    </html>

    【讨论】:

      【解决方案4】:
      window.db = getFirestore(app);
      

      app.js

      setTimeout(()=>{
          window.db.collection('cafes').get().then(snapshot => {
              console.log("test");
          });
      }, 5000);
      

      【讨论】:

      • 改成这个错误(Uncaught TypeError: Cannot read property 'collection' of undefined)
      • 你需要删除defer
      • 是的,我尝试过,但仍然出现该错误。请看看(snipboard.io/lIq9FW.jpgsnipboard.io/5XC9UW.jpg
      • 检查一下,prntscr.com/1qybyk1 现在,&lt;script type="module"&gt; 没有阻塞,所以,你需要修复它
      • 我用你的代码更新了它,但仍然出现错误(prnt.sc/1qycoit)
      猜你喜欢
      • 2023-01-23
      • 2016-11-03
      • 2011-01-05
      • 2016-01-02
      • 2013-10-06
      • 2016-12-17
      • 1970-01-01
      相关资源
      最近更新 更多