javascript - 登录并重定向到主页时无法获取 id

标签 javascript firebase firebase-authentication

我正在使用 Firebase Web 身份验证,并且希望在从登录页面登录后在主页的控制台中获取我的用户 uid。根据我所做的,没有显示 uid。请参阅下面的代码:

登录代码:

console.log("Initialisation Successful!");
const auth = firebase.auth();
var db = firebase.firestore();

function loginUser(){
    const email = document.getElementById("email").value;
    const password = document.getElementById("password").value;

    auth.signInWithEmailAndPassword(email, password)
    .then(cred => {
        alert("success");
    })
    .then(function(){
        window.location.href = "homepage.html";
    })
    .catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;
        console.log(errorCode + " " + errorMessage);
    });
}

主页代码:

console.log("Initialisation Successful!");
const auth = firebase.auth();
var db = firebase.firestore();

var user = firebase.auth().currentUser;

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        // User is signed in.
        var email = user.email;
        var uid = user.uid;
        console.log(email + " " + uid);
    } else {
    // User is signed out.
    // ...
  }
});


if (user) {
  // User is signed in.
  if (user != null) {
    email = user.email;
    uid = user.uid;  
    console.log(email + " " + uid);
  }
} else {
  // No user is signed in.
}

我该如何解决这个问题?谢谢。

最佳答案

加载了错误的脚本。 最终,正如 Taio 在评论中所说,首先 onauthstatechanged 函数记录 uid。

关于javascript - 登录并重定向到主页时无法获取 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58257256/

相关文章:

javascript - 格式化使用 JavaScript 发送的电子邮件正文

javascript - 替换 HTML 显示的 mongodb 值

android - Firebase react-native 无法访问

java - 我遇到此错误 java.lang.IndexOutOfBoundsException : Index: 0, 大小:0

javascript - 使用 Vue.js 和 FirebaseUI,身份验证成功后如何存储 authResult 对象?

swift - Flutter Firebase 电话验证码未通过短信发送

javascript - React - 如何为状态添加多个值

ios - 从 Firebase 的 URL 加载图像时,CollectionsView 性能不稳定

android - Firebase Android : How to get list inside specific child?

javascript - 如何在 VueJS Mixin 中返回值