未捕获引用错误:getAuth未定义- Firebase

6tqwzwtp  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(100)

我离开的index.html和index.js的代码来帮助我,分析如果它的工作,但身份验证不工作,因为错误时出现的测试,谢谢

index.html
<script type="module">
    // Import the functions you need from the SDKs you need
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.21.0/firebase-app.js";
    import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.21.0/firebase-analytics.js";
    import { getAuth } from "https://www.gstatic.com/firebasejs/9.21.0/firebase-auth.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: "---",
      authDomain: "---",
      databaseURL: "---",
      projectId: "---",
      storageBucket: "---",
      messagingSenderId: "---",
      appId: "---",
      measurementId: "---"
    };
  
    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const analytics = getAnalytics(app);
  </script>

index.js
getAuth(auth, (user) => {
  if (user) {
    console.log('Usuario conectado');
  } else {
    console.log('Ningún usuario conectado');
  }
});

错误:未捕获引用错误:在index.js:1:1处未定义getAuth
我试过测试分析功能,它的工作,但我不明白为什么身份验证功能不工作,如果我使用相同的系统

svujldwt

svujldwt1#

getAuth仅在<script type="module">标记中可见,因此在其他javascript文件中使用它将导致未定义的变量
你可以定义一个全局函数,并从模块标记调用它,将这些变量作为参数插入,重要的是在脚本模块标记之前定义全局函数

// load this script before script type module tag
function moduleLoadedWithParams(getAuth) {
    console.log(getAuth);
  
  auth = 'example'; // will throw error, but getAuth function is called
  getAuth(auth, (user) => {
    if (user) {
      console.log('Usuario conectado');
    } else {
      console.log('Ningún usuario conectado');
    }
  });
}
<script type="module">
    // Import the functions you need from the SDKs you need
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.21.0/firebase-app.js";
    import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.21.0/firebase-analytics.js";
    import { getAuth } from "https://www.gstatic.com/firebasejs/9.21.0/firebase-auth.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
    
    window.moduleLoadedWithParams(getAuth);    
</script>

相关问题