将数据添加到Firebase并同时重定向到其他页面

时间:2018-07-18 17:25:13

标签: javascript firebase firebase-realtime-database

我正在使用 Firebase 创建一个具有登录/注册功能的网站,问题是当用户创建新帐户时,我想将他重定向到首页并将其姓名放在 firebase中数据库。用户被重定向到主页,我无法将数据添加到 firebase数据库

请检查我的密码

signUp.addEventListener('click',() => {

const emailValue = emailField.value;
const passValue = passField.value;

if(emailValue === "" && passValue === "" || emailValue !== "" && passValue    == "" || emailValue == "" && passValue !== "") 
{
    alert('Please fill all fields')
}
else {
    const auth = firebase.auth();
    const promise = auth.createUserWithEmailAndPassword(emailValue,passValue);
    promise
    .then(() => {
        auth.signInWithEmailAndPassword(emailValue,passValue);
        let userId = auth.currentUser.uid;
        let dataRef = firebase.database().ref('users/' + userId);
        dataRef.set({
            name: nameField.value
        });
        console.log('User Signed In');
        return './homepage.html';
    })
    .then((address) => {
        window.location.href = address;
    })
    .catch(e => {
    console.log(e.message);
    })

}

});

先谢谢了:)

1 个答案:

答案 0 :(得分:1)

createUserWithEmailAndPassword返回一个user object,因此无需重新验证凭据。请尝试以下方法:

signUp.addEventListener('click', () => {
  const emailValue = emailField.value;
  const passValue = passField.value;
  if (emailValue === "" && passValue === "" || emailValue !== "" && passValue == "" || emailValue == "" && passValue !== "") {
    alert('Please fill all fields')
  } else {
    firebase.auth().createUserWithEmailAndPassword(emailValue, passValue).then(function (user) {
      const user_data = {
        wo: 0
      };
      const promise = firebase.app().database().ref(`/users/${user.uid}`).set(user_data);
      promise.then(() => {
        window.location.href = './homepage.html';
      });
    }, function (error) {
      var errorCode = error.code;
      var errorMessage = error.message;
      console.log(errorMessage);
    });
  }
});