繁体   English   中英

用户成功登录后如何将登录页面重定向到主页?

[英]How do I redirect my login page to the homepage after successful sign in by user?

I am having a lot trouble redirecting a user from the login page to the homepage after they successfully login (with the right email and password that they created. My website is written in HTML, CSS and Javascript, and I am using firebase for authentication.我到处检查过,但似乎找不到有效的解决方案。我尝试了下面的方法(最后一个 function 是我的重定向尝试),它似乎有效,但是,它会导致无限的页面刷新/重新加载。有人可以请帮帮我?

function signUp() {
      
   var email = document.getElementById("email");
   var password = document.getElementById("password");

   const promise = auth.createUserWithEmailAndPassword(email.value, password.value);
   promise.catch(e => alert(e.message));

   alert("Registered");

}

function signIn() {
      
   var email = document.getElementById("email");
   var password = document.getElementById("password");

   const promise = auth.signInWithEmailAndPassword(email.value, password.value);
   promise.catch(e => alert(e.message));

   alert("Logged in " + email.value);

}

function signOut() {
   auth.signOut();
   alert("Logged out");
}

firebase.auth().onAuthStateChanged(function (user) {
   if (user) {
      var email = user.email;
      alert("Active user: " + email);
      window.location.href = "/Users/Me/Desktop/Website HTML/home.html";
   }
   else {
     alert("No active user");
     window.location.href = "/Users/Me/Desktop/Website HTML/login.html";

   }
})

我认为您的代码导致无限重定向循环的原因是它没有指定何时不应发生重定向。 此示例是在进行重定向之前检查当前页面的示例。

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        var email = user.email;
        alert("Active user: " + email);
        if (window.location.href.indexOf("home.html") == -1) {
            window.location.href = "/Users/Me/Desktop/Website HTML/home.html";
        }
    } else {
        alert("No active user");
        if (window.location.href.indexOf("login.html") == -1) {
            window.location.href = "/Users/Me/Desktop/Website HTML/login.html";
        }
    }
})

您应该对 signIn 方法进行重定向...

const promise = auth.signInWithEmailAndPassword(email.value, password.value);

promise
  .then(() => {
    //handle your redirection here

    //add any alerts or console logs here
  })
  .catch(e => alert(e.message));

//on another note.. the alert you have here will always trigger before
//the promise resolves, so you should have it inside the 'then' method
alert("Logged in " + email.value);

然后只使用“onAuthStateChanged”方法来检查身份验证

firebase.auth().onAuthStateChanged(function (user) {
 if(!user) 
 {
   alert("No active user");
   window.location.href = "/Users/Me/Desktop/Website HTML/login.html";
 }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM