Skip to content Skip to sidebar Skip to footer

Trouble Connecting Firebase Database To Express.js Server

Good afternoon everyone I am in a little trouble trying to connect my express server to my firebase database. I am making an app that makes api calls to my express server that in

Solution 1:

Using this code I was able to connect to firebase on the backend:

"use-strict"var express = require("express");
//dependenciesvar request = require("request");
varOptions = require("./router.js")
var app = express();
var bodyParser = require("body-parser");
varFirebase = require("firebase");

Firebase.initializeApp({
  databaseURL: "[databaseURL]",
  serviceAccount: {
  "type": "service_account",
  "project_id": "haloapp-5cfe2",
  "private_key_id": "[some number]",
  "private_key": "[redacted]",
  "client_email": "haloappservice@haloapp-5cfe2.iam.gserviceaccount.com",
  "client_id": "[my client ID]",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/haloappservice%40haloapp-5cfe2.iam.gserviceaccount.com"
}

});

// links to my firebase databasevar db = Firebase.database();
//sets the reference to the root of the database, or the server I'm not quite sure.var ref = db.ref("/");

And here is an example API call that sends data to the database:

//Event Listener when there is a POST request made from public/request.js
app.post("/statSearch", function(req, res){
    // In this case the req is the POST request and the request body is the data I sent along with it. Refer to request.jsvar search = req.body.search;

    var statsOptions = new Options("https://www.haloapi.com/stats/h5/servicerecords/warzone?players="+search);

        request(statsOptions, function (error, response, body) {
          if (error) thrownewError(error);
          // This is necessary because the body is a string, and JSON.parse turns said string into an objectvar body = JSON.parse(response.body)

          var playerData = {
            gamertag: body.Results[0].Id,
                totalKills: body.Results[0].Result.WarzoneStat.TotalKills,
                totalDeaths: body.Results[0].Result.WarzoneStat.TotalDeaths,
                totalGames: body.Results[0].Result.WarzoneStat.TotalGamesCompleted
          };
        res.send(playerData)
        //console.log(playerData);// creates a child named "user" in my databasevar userRef = ref.child("user");
    // populates the child with the playerData object successfully.// Every time a new POST request is issued the user's data resets.
    userRef.set(playerData)
        });
});

This code writes data to my database!

Post a Comment for "Trouble Connecting Firebase Database To Express.js Server"