简体   繁体   中英

firebase auth with email and password not working

I wrote a webapp that has a login form but it does not work and it does not returns any error. Here the main.js function and the HTML code that calls that.

function signinUser() {
    var email = document.getElementById("inputEmail").value;
    var password = document.getElementById("inputPassword").value;

    firebase.auth().signInWithEmailAndPassword(email, password).then((userCredential) => {
        var user = userCredential.user;

        console.log(user);
    }).catch((error) => {
        var errorCode = error.code;
        var errorMessage = error.message;

        if (errorCode === 'auth/wrong-password')
            alert("Password errata!");

        console.log("Error code: " + errorCode);
        console.log("Error message: " + errorMessage);
    });
}

This is the HTML code on my login page:

<form id="login" class="form-signin position-absolute top-50 start-50 translate-middle">
    <img class="mb-4" src="img/logo.png" alt="" width="72" height="72">
    <h1 class="h3 mb-3 fw-normal">Login</h1>
    <label for="inputEmail" class="visually-hidden">Email address</label>
    <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
    <label for="inputPassword" class="visually-hidden">Password</label>
    <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
    <div class="checkbox mb-3">
        <label>
            <input type="checkbox" value="remember-me"> Remember me
        </label>
    </div>
    <button class="w-100 btn btn-lg btn-primary" type="submit" onclick="signinUser();">Sign in</button>
    <p class="mt-5 mb-3 text-muted">&copy; 2021</p>
</form>

In your form you declare your button as a button of type submit :

<button class="w-100 btn btn-lg btn-primary" type="submit" onclick="signinUser();">Sign in</button>

This results in the fact that your form is submitted before the asynchronous Firebase signInWithEmailAndPassword() method is completed.

Changing the button to type="button" will solve the problem (See W3 specification ). The form will not be submitted but this is not a problem at all: you don't want the form to be submitted, you just want the Firebasse method to be called with the correct values taken from the form (ie email and password ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM