Firebase邮箱验证异常:user为null无法发送验证邮件求助
Hey there! I see exactly what's causing your issues—let's fix them one by one.
1. Why you're getting "user is null"
The createUserWithEmailAndPassword() method runs asynchronously. When you immediately call firebase.auth().currentUser right after it, the user creation process hasn't finished yet, so currentUser is still null. You need to wait for the promise to resolve before accessing the user object.
2. Fixing the Sign-Up & Verification Code
Here's the corrected sign-up handler that properly waits for the user to be created before sending the verification email:
// Add create user event btnSignUp.addEventListener('click', e => { // Get email and password const email = txtEmail.value; const pass = txtPassword.value; const auth = firebase.auth(); // Wait for the user creation promise to resolve auth.createUserWithEmailAndPassword(email, pass) .then(userCredential => { // Now we have access to the user object via userCredential.user const user = userCredential.user; // Send verification email return user.sendEmailVerification(); }) .then(() => { console.log("Verification email sent!"); // Optional: Redirect to a "check your email" page here }) .catch(e => console.log(e.message)); });
3. Fixing the Auth State Listener (Enforce Verification)
Your current listener has a couple of issues: it doesn't check if user exists first, and the order of window.location and signOut might cause unexpected behavior. Here's the improved version:
// Add a realtime listener firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in, check if email is verified if (user.emailVerified) { console.log('Email is verified'); console.log(user); // Allow access to your protected content here } else { // Email not verified: sign out and redirect alert("Please verify your email before accessing this page."); firebase.auth().signOut() .then(() => { window.location = "index.html"; }); } } else { // No user signed in, redirect to login/sign-up window.location = "index.html"; } });
Key Notes
- Always handle Firebase auth methods with
.then()/.catch()or async/await to ensure you're working with valid user objects after operations complete. - When redirecting after sign-out, wrap the
window.locationcall inside thesignOut()promise's.then()to make sure the sign-out finishes first. - You might want to add a dedicated "check your email" page instead of just alerting, to improve user experience.
内容的提问来源于stack exchange,提问作者nboris55

