Firebase .on('value')无效

CEN*_*EDE 4 javascript firebase firebase-realtime-database

林右下面这个视频在这里.

这是我的代码.

的index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Fire Test</title>
        <script src="https://www.gstatic.com/firebasejs/3.2.1/firebase.js"></script>
    </head>
    <body>

        <!-- Value -->
        <pre id="object"></pre>

        <script src="app.js"></script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

app.js

(function () {

    // Initialize Firebase
    var config = {
        apiKey: "AIzaSyCOJZqfas4gxwEYBbRNyyIy7Z9vEsTx4ME",
        authDomain: "fire-test-e2185.firebaseapp.com",
        databaseURL: "https://fire-test-e2185.firebaseio.com",
        storageBucket: "fire-test-e2185.appspot.com",
    };

    firebase.initializeApp(config);

    var preObject = document.getElementById('object');


    // Create reference 
    var dbRefObject = firebase.database().ref().child('object')

    console.log('test log'); // logging

    // Sync object changes
    dbRefObject.on('value', function (snap) {
        console.log(snap.val()); // not logging
    });

    console.log('test log'); // logging
})();
Run Code Online (Sandbox Code Playgroud)

产量

在此输入图像描述

BTW

这是我测试项目的结构,以防万一.

fire-test
    |_ index.html
    |_ app.js
Run Code Online (Sandbox Code Playgroud)

和IM上运行它apache/var/www/html/fire-test

http://localhost/fire-test/

CEN*_*EDE 10

实际上firebase的数据库有它的身份验证,我发现我的数据库上的规则没有正确设置(公开).

我改变了这个:

{
    "rules": {
        ".read": "auth != null",
        ".write": "auth != null"
    }
}
Run Code Online (Sandbox Code Playgroud)

{
    "rules": {
        ".read": true,
        ".write": true
    }
}
Run Code Online (Sandbox Code Playgroud)

"auth != null"true

注意

以这种方式设置规则是个坏主意.我们不希望任何人访问该root节点.虽然在这个答案中,这只是为了测试firebase连接.

  • 杰出的!让我免于刮伤头发。 (3认同)