2016-08-26 53 views
0

我有這樣的代碼,將用戶登錄在:輸入正確憑證時顯示歡迎頁面?

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。 我希望它說歡迎用戶(用戶是他們登錄的電子郵件)

回答

0

爲了做到這一點,您需要檢查錯誤,然後進行重定向。

下面是從火力地堡文檔示例代碼:

// 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(電子郵件,密碼)返回一個包含firebase.Promise非空firebase.User

你可以在這裏閱讀更多:https://firebase.google.com/docs/reference/js/firebase.Promise#then

對於您可以使用Location.replace()重定向。這是一個文檔。鏈接:https://developer.mozilla.org/en-US/docs/Web/API/Location/replace

希望這有助於!

+0

它似乎並沒有進入第二部分。是因爲它只有在出現錯誤時才進入函數? –

+0

嘿,對不起!我更新了代碼以滿足您的需求,應該工作。 – MEGADEVOPS

0

始終使用onAuthStateChanged()來跟蹤用戶的登錄或註銷狀態。

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

上述代碼將確保如果用戶成功登錄,它們將被重定向到歡迎頁面。