【发布时间】:2021-04-09 23:58:45
【问题描述】:
我目前正在做我大学最后一年的项目,它使用 FERN 堆栈和 Ionic 创建一个显示温度信息的应用程序。我面临的问题是,当我刷新浏览器时,它会将用户注销。
是否有可能实现一种方法来检查用户身份验证状态是否已通过 Axios 请求更改为 onAuthStateChanged() 或者我应该只导入 firebase admin 以便我可以在 Ionic 应用程序本身中使用身份验证功能?
我已经使用 Auth 作为 API 请求温度的中间件,所以我几乎要实现 Auth 模块两次,但如果它更容易使用 onAuthStateChanged() 函数,我不介意以这种方式实现它。我还在应用程序的后端做登录功能和注册功能。
截至目前,我将用户登录并存储了一个令牌:
const handleLogin = async () => {
await axios.post('http://localhost:3000/login', {
email: email,
password: password
}).then(res => {
localStorage.setItem('Token', `Bearer ${res.data.token}`);
console.log(res);
onLogin();
}).catch(err => {
console.log(err);
});
}
这是我的 loginUser 函数,它发回令牌:
exports.loginUser = (req, res) => {
const user = {
email: req.body.email,
password: req.body.password
}
const { valid, errors } = validateLoginData(user);
if (!valid) return res.status(400).json(errors);
firebase
.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then((data) => {
return data.user.getIdToken();
})
.then((token) => {
return res.json({ token });
})
.catch((error) => {
console.error(error);
return res.status(403).json({ message: 'Invalid email or password. Please try again'});
})
};
在我的代码中实现 onAuthStateChanged() 函数的最佳方式是什么?我在一个教程中看到,当他们在其中登录用户时,使用 IndexedDB 来存储 authUser 键和值。我的代码不只存储令牌信息。
【问题讨论】:
标签: node.js reactjs firebase ionic-framework axios