JS Ошибка «Firebase не определена» при попытке инициализации - PullRequest
1 голос
/ 16 марта 2020

Я работаю с Glitch.com для моего первого проекта IoT (также нет опыта работы с front / back end). Я установил датчик влажности и добавил немного кода в Arduino. Влага загружается из Arduino в базу данных Firebase в реальном времени.

Теперь, когда я пытаюсь добавить эти данные из Firebase на мою веб-страницу, я продолжаю сталкиваться с той же ошибкой. После нескольких неудачных попыток я решил просто сделать ремикс на существующий проект для подключения Firebase. После заполнения всей моей собственной информации Firebase (auth, url ...) я все еще сталкивался с той же самой проблемой, 'Firebase не определен'. Эта ошибка происходит по этим 3 правилам:

firebase.initializeApp(config);
var rootRef = firebase.database().ref();
var myDBConn = firebase.database().ref("Moisture");

Полный код (для некоторого контекста):

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

    // Initialize Firebase
    // TODO: Replace with your project's customized code snippet
  var config = {
        apiKey: "your apiKey from firebase website",
        authDomain: "projectId.firebaseapp.com",
        databaseURL: "https://databaseName.firebaseio.com",
        storageBucket: "bucket.appspot.com",
      };
        firebase.initializeApp(config);

        var rootRef = firebase.database().ref();


  // List to hold my moisture value
  var myMoisture = [];

  // Define database connection to correct branch, Moisture
  var myDBConn = firebase.database().ref("Moisture");

  // Function that acts when a 'new child is added to the DB' - i.e. new data is added this function runs.
  myDBConn.on("child_added", function(data, prevChildKey){

    // The data returned from the branch is put into a variable, dataPoint
    var dataPoint = data.val();

    // Convert the 'Temp' field from dataPoint into integers, then put them into the myTemps list
    myMoisture.push(parseInt(dataPoint.Temp));

    // Add all the Temps and get the total
    var totalT = 0;
    var i=0;
    for (i=0; i<myMoisture.length; i++){
      totalT += myMoisture[i];
    }

    // Create an average by dividing the sum of temps by the number of temps
    var average = totalT / myMoisture.length;

    // Update the page elements with the average and the last item (most recent) off the list 
    document.getElementById("averageT").innerHTML=average;
    document.getElementById("LiveT").innerHTML=myMoisture[myMoisture.length - 1];
  });

Еще одна вещь, которая меня интересует, это то, что делает datapoint.Temp означает? Оригинальный код был сделан для веб-страницы, отображающей текущую температуру и среднюю температуру, однако я хочу значение влажности. Мне все еще нужно немного отредактировать код, но я хочу убедиться, что соединение Firebase работает, прежде чем я начну на этом.

1 Ответ

1 голос
/ 16 марта 2020

Вы должны включить свой код JavaScript в тег script следующим образом:

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

<script>
    // Initialize Firebase
    // TODO: Replace with your project's customized code snippet
  var config = {
        apiKey: "your apiKey from firebase website",
        authDomain: "projectId.firebaseapp.com",
        databaseURL: "https://databaseName.firebaseio.com",
        storageBucket: "bucket.appspot.com",
      };
        firebase.initializeApp(config);

        var rootRef = firebase.database().ref();


  // List to hold my moisture value
  var myMoisture = [];

  // Define database connection to correct branch, Moisture
  var myDBConn = firebase.database().ref("Moisture");

  // Function that acts when a 'new child is added to the DB' - i.e. new data is added this function runs.
  myDBConn.on("child_added", function(data, prevChildKey){

    // The data returned from the branch is put into a variable, dataPoint
    var dataPoint = data.val();

    // Convert the 'Temp' field from dataPoint into integers, then put them into the myTemps list
    myMoisture.push(parseInt(dataPoint.Temp));

    // Add all the Temps and get the total
    var totalT = 0;
    var i=0;
    for (i=0; i<myMoisture.length; i++){
      totalT += myMoisture[i];
    }

    // Create an average by dividing the sum of temps by the number of temps
    var average = totalT / myMoisture.length;

    // Update the page elements with the average and the last item (most recent) off the list 
    document.getElementById("averageT").innerHTML=average;
    document.getElementById("LiveT").innerHTML=myMoisture[myMoisture.length - 1];
  });

</script>

Подробнее JavaScript см. https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics и / или https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...