Javascript - firebase.auth().onAuthStateChanged 在登录/注销时不触发

rgo*_*alv 8 html javascript web firebase firebase-authentication

我有以下代码:

var config = {
       apiKey: "xxxxx",
       authDomain: "xxxxx",
       databaseURL: "xxxxx",
       projectId: "xxxxx",
       storageBucket: "xxxxx",
       messagingSenderId: "xxxxx"
};

firebase.initializeApp(config);

$("#loginButton").on('click', function(){
    logIn($("#email").val(), $("#pwd").val());
});

$("#logoutButton").on('click', function(){
   firebase.auth().signOut();
   console.log("clicked logout button");
});

function logIn(email, password){
   firebase.auth().signInWithEmailAndPassword(email,    password).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    alert(error.message);
  });
}

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      console.log("Signed in");                  
      firebase.auth().currentUser.getIdToken(true).then(function(idToken) {
        // Send token to your backend via HTTPS
        // ...
        console.log("Token = " + idToken);
        console.log("Logged in!");
        $("#loginButton").val(idToken);
        $("#loginForm").submit();
      }).catch(function(error) {
           // Handle error
           console.log(error);
      });
   }
   else{
       console.log("User signed out");
   }
});
Run Code Online (Sandbox Code Playgroud)

我在这里尝试完成的是:用户填写电子邮件和密码字段,单击带有 的按钮id="loginButton",我登录,获取令牌 ID 并将其发送到服务器(这种形式是否推荐发送它的黑客方式?)和通过我的 Express 应用程序 (Node.js) 中的 Admin SDK 验证令牌 ID。

重点是。用户确实登录和退出(通过刷新页面,我可以看到打印了“登录”和“用户退出”)。

但是为什么onAuthStateChanged当它应该观察/监听 auth 状态的每个变化时只调用一次?

为什么我可以登录和退出,但onAuthStateChanged仅在开始时(页面加载时)调用,而在单击按钮(loginButtonlogoutButton)时不再调用?

小智 3

首先,更改firebase.auth().currentUser.getIdTokenuser.getIdToken您的身份验证状态侦听器。

其次,您应该向 signInWithEmailPassword 承诺添加 then 并打印一些消息以查看登录是否成功。

最后,如果您两次登录同一用户且中间没有注销,则不会触发身份验证状态侦听器。如果您想在每次用户登录时触发一些逻辑,您应该将其放入 signInWithEmailPassword Promise 的 then 块中。

  • 此事有进展吗?我在反应本机应用程序中面临几乎相同的问题 (4认同)