【问题标题】:Initialize firebase in index.html file, but index.js throws a ReferenceError在 index.html 文件中初始化 firebase,但 index.js 会抛出 ReferenceError
【发布时间】:2021-07-07 01:28:07
【问题描述】:

我在 index.html 中初始化firebase。但是const db = firebase.firestore(); 行在index.js 中抛出错误。

firebase 是否应该在范围内,因为我在 index.html 中加载了所有 firebase 模块并初始化 firebase 然后加载`index.js?

错误: ReferenceError: firebase is not defined 应用结构:

/
|--functions
     |
     |---- index.js
|--public
     |
     |---- index.html
     |---- app.js

index.js:

const functions = require('firebase-functions');
const cors = require('cors')({ origin: true});
const admin = require('firebase-admin');
const serviceAccount = require('./service-account.json');
const db = firebase.firestore();
const auth = firebase.auth();

app.js:

var ui = new firebaseui.auth.AuthUI(firebase.auth());

var uiConfig = {
    signInSuccessUrl: '/',
    callbacks: {signInSuccess: true},
    signInOptions: [
        {
            provider:firebase.auth.EmailAuthProvider.PROVIDER_ID,
            requireDisplayName: false
        },
        firebase.auth.GoogleAuthProvider.PROVIDER_ID,
        firebaseui.auth.AnonymousAuthProvider.PROVIDER_ID,
        {
            provider: firebase.auth.PhoneAuthProvider.PROVIDER_ID,
            recaptchaParameters: {size: 'invisible'},
        }
    ],
};

ui.start('#firebaseui-auth-container', uiConfig);
if (ui.isPendingRedirect()) {ui.start('#firebaseui-auth-container', uiConfig);}

var handleSignedInUser = function(user) {
    console.log('LOOOOOGGGG');
    document.getElementById('user-signed-in').style.display = 'block';
    document.getElementById('user-signed-out').style.display = 'none';
    document.getElementById('name').textContent = user.displayName ? user.displayName : user.phoneNumber;
    document.getElementById('email').textContent = user.email;
    document.getElementById('phone').textContent = user.phoneNumber;
    if (user.photoURL) {
        var photoURL = user.photoURL;
        // Append size to the photo URL for Google hosted images to avoid requesting
        // the image with its original resolution (using more bandwidth than needed)
        // when it is going to be presented in smaller size.
        if ((photoURL.indexOf('googleusercontent.com') != -1) ||
            (photoURL.indexOf('ggpht.com') != -1)) {
            photoURL = photoURL + '?sz=' +
                document.getElementById('photo').clientHeight;
        }
        document.getElementById('photo').src = photoURL;
        document.getElementById('photo').style.display = 'block';
    } else {
        document.getElementById('photo').style.display = 'none';
    }
    nameinDB = usersRef.where("name","==",user.name);
    emailinDB = usersRef.where("name","==",user.email);

    console.log(nameinDB);
    console.log(emailinDB);
    console.log("bort");

};

var handleSignedOutUser = function() {
    document.getElementById('user-signed-in').style.display = 'none';
    document.getElementById('user-signed-out').style.display = 'block';
    ui.start('#firebaseui-auth-container', uiConfig);
};

firebase.auth().onAuthStateChanged(function(user) {
    document.getElementById('loading').style.display = 'none';
    document.getElementById('loaded').style.display = 'block';
    user ? handleSignedInUser(user) : handleSignedOutUser();
});

function recaptchaVerifierInvisible() {
    function onSignInSubmit() {
      // TODO(you): Implement
    }
    window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
      'size': 'invisible',
      'callback': (response) => {
        // reCAPTCHA solved, allow signInWithPhoneNumber.
        onSignInSubmit();
      }
    });
  }
  

 var initApp = function() {
    document.getElementById('sign-out').addEventListener('click', function() {
        console.log('clicked log out');
        firebase.auth().signOut();
    });
};

window.addEventListener('load', initApp);
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
  'size': 'invisible',
  'callback': (response) => {onSignInSubmit();}
});

//DB 
console.log(auth);

index.html

<head>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Imperial Zhao</title>

    <script src="https://www.gstatic.com/firebasejs/7.16.1/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.16.1/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.16.1/firebase-firestore.js"></script>
    <script src="https://www.gstatic.com/firebasejs/ui/4.8.0/firebase-ui-auth.js"></script>
    <link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/4.8.0/firebase-ui-auth.css" />
    <script>
       var firebaseConfig = {
            apiKey: "AIzaSyB_8VRAvuzIvPyFGbL4sX4VA_pa7V0LJjE",
            authDomain: "zhaobot.firebaseapp.com",
            databaseURL: "https://zhaobot-default-rtdb.firebaseio.com",
            projectId: "zhaobot",
            storageBucket: "zhaobot.appspot.com",
            messagingSenderId: "40454341298",
            appId: "1:40454341298:web:5d9b4554f7c1296c507fab",
            measurementId: "G-1J082S2W8B"
            };
      
            firebase.initializeApp(firebaseConfig);
    </script>
  
    <script src="functions/index.js" defer></script>
  </head>
  
  <body>
  
    <h1>The Imperial Zhao</h1>
    <div id="loading">Loading...</div>

    <div id="loaded" class="hidden">
        <div id="user-signed-out" class="hidden">
            <div id="firebaseui-auth-container"></div>
        </div>

        <div id="user-signed-in" class="hidden">    
            <div id="userDetails">
                <div id="name"></div>
            </div>    
            <button id="sign-out" class="btn btn-primary">Sign Out</button>
        </div>
    </div>

  </body>

【问题讨论】:

    标签: javascript node.js firebase


    【解决方案1】:
    firebase is not defined
    

    表示你没有在文件中导入firebase。

    firebase 库太多了,所以我无法在这里找到哪一个,但我相信你知道你在使用哪一个。

    判断错误,你需要的是:

    const firebase = require('...');
    

    【讨论】:

    • index.html中第一个script标签不导入吗?
    • 但 index.js 中的代码运行时未定义。如果您不想将其包含在 index.js 中,请确保“firebase”可用。
    • 但是,如果我将 console.log(firebase) 放在 HTML 中的 initializeApp 之后,它会正确打印。我用defer 在这些语句之后加载index.js。为什么firebase会超出范围并变得未定义?另外,如果我var firebase = require('firebase'),那么firebase.firestore 是未定义的,尽管这可能是一个单独的错误。
    • 我相信 functions/index.js 不是浏览器 JavaScript 而是服务器端。因此,在 index.js 中导入 firebase 是很有必要的。
    • 函数/里面有node_modules吗?
    猜你喜欢
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 2015-12-27
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2020-10-17
    相关资源
    最近更新 更多