简体   繁体   English

firebase 身份验证与 email 和密码不起作用

[英]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.我编写了一个具有登录表单的 web 应用程序,但它不起作用并且它不返回任何错误。 Here the main.js function and the HTML code that calls that.这里的 main.js function 和调用它的 HTML 代码。

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:这是我登录页面上的 HTML 代码:

<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 :在您的表单中,您将按钮声明为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.这导致您的表单在异步 Firebase signInWithEmailAndPassword()方法完成之前提交。

Changing the button to type="button" will solve the problem (See W3 specification ).将按钮更改为type="button"将解决问题(参见W3 规范)。 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 ).表单将不会被提交,但这根本不是问题:您不希望提交表单,您只希望使用从表单中获取的正确值(即emailpassword )调用 Firebasse 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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