createUserWithEmailAndPassword 未定义
如何在 auth.js 文件中访问 index.html 中初始化的 auth 对象?我应该将其作为参数传递吗?还是有更好的方法在模块化 JavaScript 设置中管理 Firebase 身份验证?如能提供任何指导,我将不胜感激!
<form id="signup-form">
<div class="input-field">
<input type="email" id="signup-email" required />
<label for="signup-email">Email address</label>
</div>
<div class="input-field">
<input type="password" id="signup-password" required />
<label for="signup-password">Password</label>
</div>
<button type="submit">Sign Up</button>
</form>
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.14.1/firebase-app.js";
import { getAuth } from "https://www.gstatic.com/firebasejs/10.14.1/firebase-auth.js";
const firebaseConfig = {
apiKey: "API_KEY",
authDomain: "AUTH_DOMAIN",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "MESSAGING_SENDER_ID",
appId: "APP_ID",
measurementId: "MEASUREMENT_ID"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app); // Initializes the auth service
</script>
<script src="scripts/auth.js"></script>
const signupForm = document.querySelector('#signup-form');
signupForm.addEventListener('submit', (e) => {
e.preventDefault();
const email = signupForm['signup-email'].value;
const password = signupForm['signup-password'].value;
createUserWithEmailAndPassword(auth, email, password).then((cred) => {
console.log(cred);
}).catch((error) => {
console.error("Error creating user:", error);
});
});
为了能够调用
createUserWithEmailAndPassword
,您需要在要调用的特定文件中导入该特定函数。与在第一个文件中导入然后调用的方式类似,您也需要在第二个文件中getAuth
导入然后调用。createUserWithEmailAndPassword
在 HTML 中标记
auth.js
为模块(以便您可以import
在其中使用):然后就
auth.js
其本身而言进而: