首页 > 解决方案 > 如何解决未定义的 const auth?

问题描述

我想使用firebase身份验证,所以我在我的html正文脚本中声明了一个名为auth的常量,我想在我的auth.js文件中使用它,但它说它没有定义,我想知道如何解决问题。这是我写的代码:这是我的 html 文件中的代码:

<!-- Firebase -->
<script type="module">
    // Import the functions you need from the SDKs you need
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js";
    import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-analytics.js";
    import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-auth.js";
    import { getFirestore } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-firestore.js";
    // TODO: Add SDKs for Firebase products that you want to use

    // Your web app's Firebase configuration
    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
    const firebaseConfig = {
        apiKey: "AIzaSyC3GLIN5TBmCDoTfy0dEOgOdvVvqNw-ric",
        authDomain: "auth-project-38aaa.firebaseapp.com",
        projectId: "auth-project-38aaa",
        storageBucket: "auth-project-38aaa.appspot.com",
        messagingSenderId: "431888894254",
        appId: "1:431888894254:web:71bb9b250fbb8a21edd2bf",
        measurementId: "G-6BBPCJ3814"
    };
    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const analytics = getAnalytics(app);
    const auth = getAuth(app);
    const db = getFirestore(app);
                
</script>
<!-- JS -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="js/auth.js"></script>

这是我的 auth.js 中的代码:

const signUpForm = document.querySelector('#register-form');

signUpForm.addEventListener('submit', (e) => {
    e.preventDefault();
    // get user info
    const name = signUpForm['name'].value;
    const email = signUpForm['email'].value;
    const pass = signUpForm['pass'].value;
    const rePass = signUpForm['re_pass'].value;
    const agreeTerm = signUpForm['agree-term'].value;

    console.log(name, email, pass, rePass, agreeTerm);
    // sign up the user
    auth.createUserWithEmailAndPassword(email, pass).then(cred => {
        console.log(cred); 
    });
});  

标签: javascripthtmlfirebase-authentication

解决方案


auth.createUserWithEmailAndPassword适用于 Firebase SDK v8 及更早版本,或适用于 v9 中的兼容模式。

新语法根据创建用户的文档:

createUserWithEmailAndPassword(auth, email, pass).then(cred => {
    ...
});

推荐阅读