createUserWithEmailAndPassword重定向导致错误

时间:2017-08-06 19:27:11

标签: authentication firebase firebase-authentication window.location

我希望在注册后将用户重定向到我网站的一部分,而不是登录 所以在createUserWithEmailAndPassword函数的最后我改变了window.location,一切正常,我确实收到错误,因为函数被中断了

我该如何避免这种情况?有signInWithRedirect和getRedirectResult,但Firebase文档不包含电子邮件作为提供者,只有facebook

我可以尝试捕捉错误,但也许有更优雅的方法来解决这个问题?

function handleSignUp() {
    var email = document.getElementById('email').value;
    var password = document.getElementById('password').value;
    if (email.length < 4) {
        alert('Please enter an email address.');
        return;
    }
    if (password.length < 4) {
        alert('Please enter a password.');
        return;
    }
    firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;
        if (errorCode == 'auth/weak-password') {
            alert('The password is too weak.');
        } else {
            alert(errorMessage);
        }
        console.log(error);
    });
    window.location = "/add-location";
}

// console error

A network error (such as timeout, interrupted connection or unreachable host) has occured.

2 个答案:

答案 0 :(得分:1)

登录回调后重定向怎么样?

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in. So redirect:
     window.location = "/add-location";
  } else {
    // No user is signed in.
  }
});

正如docs中所述,创建后,身份验证状态会自动更改为登录状态,以便在成功登录后触发重定向。

答案 1 :(得分:1)

成功注册后只需重定向:

firebase.auth().createUserWithEmailAndPassword(email, password)
  .then(function(user) {
    window.location = "/add-location";
  })
  .catch(function(error) {
    ...
  });

您在承诺解决之前重定向,因此中断的操作错误。