gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:43:18 25 4
gpt4 key购买 nike

我有以下代码:

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");
}
});

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

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

但是为什么 onAuthStateChanged 应该观察/监听身份验证状态的每个更改时只调用一次?

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

最佳答案

首先,在您的身份验证状态监听器中将 firebase.auth().currentUser.getIdToken 更改为 user.getIdToken

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

最后,如果您两次登录同一用户而中间没有注销,则不会触发身份验证状态监听器。如果你想在每次用户登录时触发一些逻辑,你应该把它放在 signInWithEmailPassword promise 的 then block 中。

关于Javascript - firebase.auth().onAuthStateChanged 在登录/注销时不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50867561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com