首页 > 解决方案 > 登录页面到主页后未获取 Firebase 用户凭据

问题描述

我正在尝试使用带有纯Javascript的firebase auth进行简单的登录和注销,我不确定这是正确的方法。但这是我到目前为止所做的:
index.html我的头元素中已经有了所有必要的导入链接(firebase-app,firebase-auth)

<input type="email" name="email" id="email" placeholder="email">
<input type="password" name="password" id="password" placeholder="password">
<button type="submit" onclick="signIn()">Log in</button>
<script src="app.js"></script>

home.html我的头元素中已经有了所有必要的导入链接(firebase-app、firebase-auth)

<h1 id="email"></h1>
<button onclick="logOut()">Logout</button>
<script src="app.js"></script>

app.js

const db = firebase.firestore();
const auth = firebase.auth();
var user = firebase.auth().currentUser;

function signIn(){
  const email = document.getElementById("email").value;
  const password = document.getElementById("password").value;
  firebase.auth().signInWithEmailAndPassword(email, password)
  .then((userCredential) => {
    // Signed in
    var user = userCredential.user;
    alert("Sign In");
  })
  .catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
    alert(errorMessage);
  });
}

function logOut() {
  // [START auth_sign_out]
  firebase.auth().signOut().then(() => {
    alert("Log out");
  }).catch((error) => {
    // An error happened.
    alert(error);
  });
  // [END auth_sign_out]
}

  //[START auth_state_listener]
  firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        location.replace("home.html");
        document.getElementById("email").innerHTML = user.email  
      } else {
        // User is signed out
        // ...
        location.replace("index.html");
      }
    });

我想要实现的是,当我使用我的 firebase auth 中已经存在的电子邮件和密码登录时,我将被重定向到我的home.html,它将显示我的电子邮件,如果用户未登录,home.html将无法访问并且只会index.html显示。
该代码现在发生的情况是,在我输入我的电子邮件和密码后,将出现一个循环,其中页面将不断显示index.html并且home.html电子邮件没有显示。

标签: javascriptfirebasefirebase-authentication

解决方案


推荐阅读