当输入正确的凭据时显示欢迎页面

Show welcome page when correct credentials are entered?

本文关键字:显示 输入      更新时间:2023-09-26

我有这样一段代码,用于登录用户:

function logUserIn(){
    var email = document.getElementById('username').value;
    var password = document.getElementById('password').value;
    firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
      var errorCode = error.code;
      var errorMessage = error.message;
      console.log(errorMessage)
      console.log('didnt log in')
    });
  };

这是html:

          username:<br>
          <input id="username" type="text" name="username" ><br>
          password:<br>
          <input id="password" type="text" name="password" ><br><br>
          <input type="submit" onclick=logUserIn() value="Log in">
          <input type="submit" onclick=submitToDatabase() value="Sign Up">
          <input type="submit" onclick=getUsers() value="Get Users">

我怎样才能只使用javascript提交这些数据,所以如果他们输入正确的凭据,它会把他们带到页面,如welcome.html?我知道我可能需要使用表单和提交,但我不确定这是如何单独在JS中完成的,而不是使用PHP。我希望它是Welcome User (User是他们登录的邮箱)

为了做到这一点,您需要检查错误,然后继续进行重定向。

以下是Firebase文档中的示例代码:

// Sign in with email and pass.
// [START authwithemail]
firebase.auth().signInWithEmailAndPassword(email, password)
.then(function(user) {
  console.log(user);
  // DO YOUR REDIRECTION HERE
}).catch(function(error) {
  if(error) throw error;
});

查看更多信息。signInWithEmailAndPassword方法返回firebase.Promise。

signInWithEmailAndPassword(email, password)返回firebase。包含非空firebase的承诺。用户

您可以在这里阅读更多内容:https://firebase.google.com/docs/reference/js/firebase.Promise#then

对于重定向,可以使用Location.replace()。这是医生。链接:https://developer.mozilla.org/en-US/docs/Web/API/Location/replace

始终使用onAuthStateChanged()来跟踪用户的登录或注销状态。

//Handle Account Status
firebase.auth().onAuthStateChanged(user => {
  if(user) {
    window.location = 'welcome.html'; //If User is logged in, redirect to welcome page
  }
});

上面的代码将确保如果用户成功登录,他们将被重定向到欢迎页面。