javascript - 登录页面到主页后未获取 Firebase 用户凭据
问题描述
我正在尝试使用带有纯Javascript的firebase auth进行简单的登录和注销,我不确定这是正确的方法。但这是我到目前为止所做的:
index.html
我的头元素中已经有了所有必要的导入链接(firebase-app,firebase-auth)
<input type="email" name="email" id="email" placeholder="email">
<input type="password" name="password" id="password" placeholder="password">
<button type="submit" onclick="signIn()">Log in</button>
<script src="app.js"></script>
home.html
我的头元素中已经有了所有必要的导入链接(firebase-app、firebase-auth)
<h1 id="email"></h1>
<button onclick="logOut()">Logout</button>
<script src="app.js"></script>
app.js
const db = firebase.firestore();
const auth = firebase.auth();
var user = firebase.auth().currentUser;
function signIn(){
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
firebase.auth().signInWithEmailAndPassword(email, password)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
alert("Sign In");
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
alert(errorMessage);
});
}
function logOut() {
// [START auth_sign_out]
firebase.auth().signOut().then(() => {
alert("Log out");
}).catch((error) => {
// An error happened.
alert(error);
});
// [END auth_sign_out]
}
//[START auth_state_listener]
firebase.auth().onAuthStateChanged((user) => {
if (user) {
location.replace("home.html");
document.getElementById("email").innerHTML = user.email
} else {
// User is signed out
// ...
location.replace("index.html");
}
});
我想要实现的是,当我使用我的 firebase auth 中已经存在的电子邮件和密码登录时,我将被重定向到我的home.html
,它将显示我的电子邮件,如果用户未登录,home.html
将无法访问并且只会index.html
显示。
该代码现在发生的情况是,在我输入我的电子邮件和密码后,将出现一个循环,其中页面将不断显示index.html
并且home.html
电子邮件没有显示。
解决方案
推荐阅读
- php - PHP CodeIgniter:加载不同内容的页面
- python - 迭代期间的高效 API 请求
- r - 计数基因:错误:组合对象没有共同的序列级别
- javascript - 在 puppeteer 中循环
- mysql - 使用私有 IP 的 EC2 MySQL 连接断开与公共 IP 一起使用
- pytorch - 为什么我们需要“ state_dict = state_dict.copy() ”
- ios - 每次触摸结束时创建一个新精灵
- android - 我如何使用从 Android Studio 生成的 Keystore 在 react native 中?
- mysql - 从代码中的命令行输入 mysql 后,试图让 Mysql 命令行回到 bash?
- sql - Postgresql 尝试在函数中使用执行格式,但在合并中给出字符串格式时出现未找到列的错误