【问题标题】:User logged out of firebase server when different page loads加载不同页面时用户退出firebase服务器
【发布时间】:2020-09-20 06:40:48
【问题描述】:

我是 firebase 新手,我不知道如何让用户在转到其他页面后保持登录状态。我能够成功登录并将用户数据发布到登录页面上的控制台,但是当我转到另一个页面并尝试使用 firebase.auth().currentUser。我最初在登录完成后立即将其重定向到另一个页面,然后将其关闭以查看我是否在信息中继到服务器之前离开该页面,但这并没有解决问题。我也尝试手动设置持久性无济于事。我环顾四周,没有找到任何解决问题的方法。

这是我的登录方法(与 firebase 文档上的基本相同),当点击表单上的登录按钮时调用:

function signIn(){
    //getting credential input from form
    var email = document.getElementById('email').value;
    var password = document.getElementById('password').value;
    console.log(email, password)
    //calling firebase to sign in user
    firebase.auth().signInWithEmailAndPassword(email, password)
    .then(cred => {
        //confirmation that user signed in
        console.log("signed in");
    }).catch(function(error) {
        var errorCode = error.code;
        var errorMsg = error.message;
        if(errorCode === 'auth/wrong-password') {
            alert('Wrong Password');
        }
        else {
            alert(errorMsg);
        }
        console.log(error);
    });
};

【问题讨论】:

  • .then(cred => { //confirmation that user signed in console.log("signed in"); 这里是用户输入。您要将登录用户的应用程序定向到哪里?

标签: javascript firebase firebase-authentication


【解决方案1】:

firebase.auth().currentUser 在页面加载后需要时间来获取数据。如果您尝试立即获取它,它将是null

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

一旦 Firebase 检索到所有必要的数据,此代码将执行函数中的任何操作。 @CanUver 的回答确实提到了这段代码。

我在我的网站上显示一个加载页面,直到完成。此代码 sn-p 来自 Firebase 文档。

我不确定这是否是您的问题,但我记得遇到过这个问题。

【讨论】:

    【解决方案2】:

    如果我错了,其他人会纠正我。据我所知,当您以用户身份登录时,即使您在页面之间切换,有关该用户的信息也是永久的。也就是说,只有用户添加、更新和删除的信息才会显示在您的页面上。用户变量和其他用户信息必须在“signout”中显示。

    // Think of it as a login page. assume that the user is redirected to a page after being logged in.
    firebase.auth().signInWithEmailAndPassword(email, password)
        .then(() => {
                window.location.href = "index.html"; // let this be the page where user information should be displayed.
         }) 
    

    因此,您还需要一个处理登录和注销状态的侦听器。如果用户成功登录,您可以在此处重定向用户。

    firebase.auth().onAuthStateChanged(user => {
      if(user) {
        // this is where you can listen to user changes in index html and make your operations related to user here. 
    
    firebase.auth().signOut() //  in this section you can do the logout function. Their information will be displayed until the user makes the logout. It continues until a new user logs in.
       .then(() => {
    window.location.href = "login.html"
    }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 2021-06-10
      • 2021-02-13
      • 1970-01-01
      相关资源
      最近更新 更多