首页 > 解决方案 > Firebase 身份验证未将数据存储在本地存储中

问题描述

当用户单击“提交”时,我的应用程序成功地将用户登录到 Firebase,但 Firebase 不会将用户身份验证数据存储在 Chrome 的本地存储中。我检查了一下,Firebase 成功返回了用户对象,程序使用正确的用户 ID 打印“用户登录”。但是,当我在控制台中运行“localStorage”时,该对象不存在,并且用户身份验证不会持续存在。我不确定为什么它不起作用。这是我的代码:

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL);

function authenticate(event){
    event.preventDefault();

    let email = document.getElementById("email").value;
    let password = document.getElementById("password").value;
    
    let result = firebase.auth().signInWithEmailAndPassword(email, password)
    .then(
        (user) => {
            alert("User: " + JSON.stringify(user));   //this works
        }
    )
    .catch(console.log);
}

firebase.auth().onAuthStateChanged( function(user){
    if(user){
        console.log("user signed in");   //this works
        console.log("user id: " + firebase.auth().currentUser.uid);  
        window.location.href = "./calendar.html";
    } else {
        console.log("No user");
        window.location.href = "./index.html";
    }
});

标签: javascriptfirebasefirebase-authenticationlocal-storage

解决方案


You have to use localStorage

localStorage.setItem('userData', JSON.stringify(userDetail));

To get Data

JSON.parse(localStorage.getItem('userData'));

To remove

localStorage.removeItem('userData');

推荐阅读