[英]FireBase user authentication redirect to another page
I have created a signupPage.html to authenticate a user and and log information to the realtime database in firebase using this code:我创建了一个 signupPage.html 来验证用户身份,并将信息记录到 firebase 中的实时数据库中,使用以下代码:
signUp_button.addEventListener('click', (e) => {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
//signed up
const user = userCredential.user;
//log to database
set(ref(database, 'users/' + user.uid),{
email : email
})
//this is where page redirection
alert('User Created');
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert(errorMessage);
});
});
Then when I click my submit button everything works and the user is authenticated and information is stored into the realtime database.然后,当我单击提交按钮时,一切正常,用户通过身份验证,信息存储到实时数据库中。 Now I want to redirect the user to a login page after they submit their signup.
现在我想在用户提交注册后将他们重定向到登录页面。 In my code under "this is where page redirection", I put location.href = "login.html".
在“这是页面重定向”下的代码中,我放置了 location.href =“login.html”。 This does redirect the page and authenticate the user but it no longer stores the data into the realtime database.
这确实重定向了页面并验证了用户,但它不再将数据存储到实时数据库中。 Any suggestions?
有什么建议么?
You were close.你很亲密。
set()
is an asynchronous action, so by adding the redirect where you were, you would redirect before the set()
had the chance to execute. set()
是一个异步操作,因此通过在您所在的位置添加重定向,您将在set()
有机会执行之前重定向。 You must first wait for the set()
to finish, and then redirect.您必须首先等待
set()
完成,然后重定向。
signUp_button.addEventListener('click', (e) => {
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
createUserWithEmailAndPassword(auth, email, password)
.then(async (userCredential) => {
//signed up
const user = userCredential.user;
// log to database & wait for it to finish!
return set(ref(database, 'users/' + user.uid), {
email : email
})
})
.then(() => {
alert('User Created'); // avoid alert, it blocks user input!
// update a div with an information message instead
location.href = "login.html";
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert(errorMessage); // avoid alert, it blocks user input!
// update a div with an error message instead
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.