gpt4 book ai didi

javascript - Firebase Auth - 用户在 Firebase 注册和重定向后未登录

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:39:41 26 4
gpt4 key购买 nike

我正在使用 firebase 为用户创建一个帐户。创建帐户后,我重定向到主页,它检查我是否已登录。奇怪的是,我没有登录。

在创建帐户页面上:

createAccount() {
firebaseAuth().createUserWithEmailAndPassword(this.state.email, this.state.password).then((user) => {
// write some data to database
firebase.database().ref().child('users').child(user.uid).child('someKey').set(this.state.email).then(function() {
// send email verification
user.sendEmailVerification().then(function() {
console.log("sent email verification");
// Go to home page
this.props.history.push('/home');
}.bind(this)).catch(function(error) {
console.log("Error: account created but no verification email sent.");
}.bind(this));
}.bind(this)).catch((error) => {
console.log('Error: while writing to database');
});
// catch any error while creating user
}).catch((error) => {
console.log('Error: while creating account');
});
}

在主页上:

componentDidMount() {
firebase.auth().onAuthStateChanged(function (user) {
if (!user) {
console.log("no user logged in");
this.props.history.replace('/login'); // ISSUE: Always redirected to login, even after signup and login
return
} else {
console.log("Woo! User is logged in!");
}
}.bind(this))
}

替代尝试:

  • 我曾尝试在用户注册后显式登录,但结果相同
  • this.createAccount 替换为 () => this.createAccount 用于 onClick 处理程序(相同结果)
  • 使用 firebase.auth() 而不是 firebaseAuth()(结果相同)

有人知道我为什么没有登录吗?

** 编辑: **

下面是我如何初始化我的应用程序:

<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "XXXXXXXXX",
authDomain: "myproject.firebaseapp.com",
databaseURL: "https://myproject.firebaseio.com",
projectId: "XXXXXXXXX",
storageBucket: "XXXXXXXXX.appspot.com",
messagingSenderId: "XXXXXXXXX"
};
firebase.initializeApp(config);
</script>

可能值得注意:如果我使用一个不是刚刚创建的帐户登录(或者如果我等待一段时间然后登录到我创建的帐户),保留似乎没有问题重定向时的授权。似乎只有当我创建一个新用户然后重定向时它才会丢失登录用户。

最佳答案

我有相同的设置并且工作正常。

我在路由器顶部有我的身份验证状态更改监听器...

state = { user: null };

componentDidMount() {
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.setState({ user });
} else {
this.props.history.push('/login');
}
});
}

在 Login.js 中,我有一个连接到类似于您的登录功能的表单...

login() {
firebase
.auth()
.signInWithEmailAndPassword(this.state.email, this.state.password)
.then(res => {
this.props.history.push('/');
})
.catch(err => console.error(error));
}

我唯一能想到的就是你把history.replace,改成history.push试试。

如果这不起作用,您是否有机会设置 https://codesandbox.io/使用 mcve,我很乐意调试它 https://stackoverflow.com/help/mcve

关于javascript - Firebase Auth - 用户在 Firebase 注册和重定向后未登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49000873/

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