Firebase Web API 9.22.2模块化登录页报错排查求助
解决Firebase登录时"Undefined : Undefined"错误的方案
问题根源分析
你遇到的"Undefined : Undefined"弹窗错误,核心是代码里的几处关键逻辑和语法错误导致的,以下是具体问题和修复方案:
具体错误点及修复步骤
1. Firebase模块导入顺序错误且缺失核心方法
你直接调用了initializeApp但未导入该方法,且导入语句放在了初始化操作之后,这会导致运行时找不到方法。需要先导入所需模块:
// 先导入Firebase核心及认证模块 import { initializeApp } from "https://www.gstatic.com/firebasejs/9.22.2/firebase-app.js"; import { getAuth, onAuthStateChanged, signInWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.22.2/firebase-auth.js"; const firebaseConfig = { // 你的私密配置信息 }; const app = initializeApp(firebaseConfig); const auth = getAuth(app);
2. 登录方法传入DOM元素而非输入值
signInWithEmailAndPassword需要的是邮箱、密码的字符串值,你直接传入了DOM元素对象,应该取元素的value属性:
// 替换原代码中的登录参数 signInWithEmailAndPassword(auth, userEmail.value, userPassword.value)
3. 错误对象属性名错误
Firebase错误对象的属性是code和message,而非你写的errorCode、errorMessage,这是弹窗显示"Undefined"的直接原因:
.catch((error) => { const errorCode = error.code; const errorMessage = error.message; alert(`${errorMessage} ${errorCode} : 登录失败`) })
4. 未获取登录按钮元素且未阻止默认行为
你直接使用signin变量但未通过document.querySelector获取该按钮,同时点击事件需要阻止默认行为(比如表单提交导致页面刷新):
// 先获取登录按钮(替换为你实际的按钮ID) const signinBtn = document.querySelector("#signin"); signinBtn.addEventListener('click',(e) => { e.preventDefault(); // 阻止默认提交行为 // 后续登录逻辑 })
5. 未定义authForm导致控制台报错
代码末尾console.log中的authForm未定义,需要移除该变量或补充获取逻辑。
修复后的完整代码
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.22.2/firebase-app.js"; import { getAuth, onAuthStateChanged, signInWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.22.2/firebase-auth.js"; const firebaseConfig = { // 你的私密配置信息 }; const app = initializeApp(firebaseConfig); const auth = getAuth(app); onAuthStateChanged(auth, user => { if(user != null) { console.log('已登录!') } else { console.log('无用户'); } }); const userEmail = document.querySelector("#inputemail"); const userPassword = document.querySelector("#inputpassword"); const signinBtn = document.querySelector("#signin"); // 替换为实际按钮ID signinBtn.addEventListener('click',(e) => { e.preventDefault(); signInWithEmailAndPassword(auth, userEmail.value, userPassword.value) .then((userCredentials) => { const user = userCredentials.user; alert('用户登录成功!') }) .catch((error) => { const errorCode = error.code; const errorMessage = error.message; alert(`${errorMessage} ${errorCode} : 登录失败`) }) }) // 移除未定义的authForm,仅打印输入值 console.log(userEmail.value + " " + userPassword.value)
内容的提问来源于stack exchange,提问作者Thea Young
相关产品推荐
相关产品推荐

