开发者问题收集

当我尝试使用电子邮件进行身份验证时,我收到“未捕获的类型错误:无法读取 null 的属性‘值’”错误。为什么?

2017-11-17
1795

我正在尝试使用电子邮件设置 Firebase 身份验证,但我单击了登录按钮并收到此错误:

users.js:15 Uncaught TypeError: Cannot read property 'value' of null

它还将我发送到另一个页面(点击登录按钮后的主页)。 这里 是有关如何设置身份验证的文档的链接。

Javascript:

var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
};

firebase.initializeApp(config);

//var emailTxt = document.getElementById("emailTxt").value;
//var email = emailTxt.val();
//var password = passwordTxt.val();



$('#login').on("click", function(){
  var email = document.getElementById('emailTxt').value;
  var password = document.getElementById('passwordTxt').value;
  authClient.login("password", {
  email: $("#email").val(),
  password: $("#password").val(),
  rememberMe: $("#rememberCheckbox").val()
  });

});

firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
    // Handle Errors here.
    alert();
    var errorCode = error.code;
    var errorMessage = error.message;
    // ...
});

firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    // ...
});

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        // User is signed in.
        var displayName = user.displayName;
        var email = user.email;
        var emailVerified = user.emailVerified;
        var photoURL = user.photoURL;
        var isAnonymous = user.isAnonymous;
        var uid = user.uid;
        var providerData = user.providerData;
        // ...
    } else {
        // User is signed out.
        // ...
    }
});

firebase.auth().signOut().then(function() {
    // Sign-out successful.
}).catch(function(error) {
    // An error happened.
});

HTML:

<?php
    //CREATE USER
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Cheapest Used Tires</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"
              integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"
                integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n"
                crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"
                integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb"
                crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"
                integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn"
                crossorigin="anonymous"></script>

    </head>
    <style>
        form {
            border: 3px solid #f1f1f1;
        }

        input[type=text], input[type=password] {
            width: 100%;
            padding: 12px 20px;
            margin: 8px 0;
            display: inline-block;
            border: 1px solid #ccc;
            box-sizing: border-box;
        }

        button {
            background-color: #4CAF50;
            color: white;
            padding: 14px 20px;
            margin: 8px 0;
            border: none;
            cursor: pointer;
            width: 100%;
        }

        button:hover {
            opacity: 0.8;
        }

        .cancelbtn {
            width: auto;
            padding: 10px 18px;
            background-color: #f44336;
        }

        .imgcontainer {
            text-align: center;
            margin: 24px 0 12px 0;
        }

        img.avatar {
            width: 40%;
            border-radius: 50%;
        }

        .container {
            padding: 16px;
        }

        span.psw {
            float: right;
            padding-top: 16px;
        }

        /* Change styles for span and cancel button on extra small screens */
        @media screen and (max-width: 300px) {
            span.psw {
                display: block;
                float: none;
            }
            .cancelbtn {
                width: 100%;
            }
        }
    </style>
    </head>
    <body>

        <h2>Login</h2>

        <form action="/CMS/login.php">
            <div class="imgcontainer">
                <img src="img_avatar2.png" alt="Cheapest Used Tires Admin Logn" 
                    class="avatar">
            </div>

            <div class="container">
                <label><b>Email</b></label>
                <input id="emailTxt" type="text" 
                    placeholder="Enter Email" name="email" required>

                <label><b>Password</b></label>
                <input id="passwordTxt" type="password" 
                    placeholder="Enter Password" name="psw" required>

                <button type="submit" id="login">Login</button>
                <input type="checkbox" checked="checked"> Remember me
            </div>

            <div class="container" style="background-color:#f1f1f1">
                <button type="button" class="cancelbtn">Cancel</button>
                <span class="psw">Forgot 
                    <a href="#">password?</a>
                </span>
                <span class="psw">&nbsp; | &nbsp; </span>
                <span class="psw">Create 
                    <a href="#">account?</a>
                </span>

            </div>
        </form>

        <script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
        <script src="/users.js"></script>

    </body>
</html>
3个回答

出现此问题的原因是您在相关范围之外使用了未定义的参数(例如电子邮件和密码)。

您有两个选择:

  1. 在回调中使用 document.getElementById 来检索值。(示例 1)

  2. 使用这些值调用函数。(示例 2)

注意:像您一样声明 firebase 函数调用会引发异常,因为它们是使用未定义的参数调用的

$('#login').on("click", function(){
    // example 1
    var email = document.getElementById('emailTxt').value;
    var password = document.getElementById('passwordTxt').value;

    // email and password are defined
    firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // ...
    });
});

// example 2
function createUser(email, password) {
    firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
        // Handle Errors here.
        alert();
        var errorCode = error.code;
        var errorMessage = error.message;
        // ...
    });
}


firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        // User is signed in.
        var displayName = user.displayName;
        var email = user.email;
        var emailVerified = user.emailVerified;
        var photoURL = user.photoURL;
        var isAnonymous = user.isAnonymous;
        var uid = user.uid;
        var providerData = user.providerData;
        // ...
    } else {
        // User is signed out.
        // ...
    }
});

function logout() {
    firebase.auth().signOut().then(function() {
        // Sign-out successful.
    }).catch(function(error) {
        // An error happened.
    });
}
Ami Hollander
2017-11-17

在调用返回之前,您将离开该页面。

提交按钮(单击时)的默认行为是发布表单。您必须阻止这种情况发生。(因为您正在通过 AJAX 发布值)

使用 event.preventDefault()

$('#login').on("click", function(event){

  event.preventDefault();

  var email = document.getElementById('emailTxt').value;
  var password = document.getElementById('passwordTxt').value;
  authClient.login("password", {
  email: $("#email").val(),
  password: $("#password").val(),
  rememberMe: $("#rememberCheckbox").val()
  });
U.P
2017-11-19

我没有收到任何错误,我只是用你的 html 创建了一个小提琴,并更改了 JavaScript。我可以控制用户输入的值。

$('#login').on("click", function(event) {
  event.preventDefault();

  var email = document.getElementById('emailTxt').value;
  var password = document.getElementById('passwordTxt').value;
  console.log($("#rememberCheckbox").is(":checked"));
  console.log(email);
  console.log(password);
  authClient.login("password", {
    email: email,
    password: password,
    rememberMe: $("#rememberCheckbox").is(":checked")
  });
})

检查小提琴 https://jsfiddle.net/suhailsulu/ezzxd1th/2/

suhail c
2017-11-23