无法连接Firebase数据库到Express.js服务器 [英] Trouble connecting Firebase database to Express.js server

查看:150
本文介绍了无法连接Firebase数据库到Express.js服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家下午好,我试图把我的快递服务器连接到我的Firebase数据库时遇到一些麻烦。我正在制作一个应用程序,使api调用我的快递服务器,反过来从我的客户端发送的信息使api调用到此晕api。从那里从晕的服务器给我回来的信息被送回到我的快递服务器,它给我的客户端对象填充DOM。



上面所描述的一切,我已经开始工作了,但是现在我想把一个firebase数据库合并起来,事情并不是那么完美。我想要能够做的是添加更多的功能与我的应用程序。所以当这个API调用是从我的快递服务器( app.js )发送到halo的服务器时,我想将数据发送到我的firebase数据库而不是客户端。对我来说,在实践中,取而代之的是我从halo那里得到的数据对象,我现在只是把它称为晕,因为它更容易,并将其发送到我的firebase数据库。从那里我将使用数据库来填充DOM。

正如我前面提到的那样,在实践中这证明要困难得多。我需要首先使用firebase,因为我需要添加CRUD功能到这个应用程序,所以只是不使用它是不可能的。目前在运行我的服务器时,在运行nodemon src / app.js之后,在命令行中收到此错误:

  / Users / MMac /Desktop/haloApp/src/app.js:28 
var dbReference = new Firebase(https://haloapp-5cfe2.firebaseio.com/);
^

TypeError:Firebase不是一个函数
在Object。< anonymous> (/Users/MMac/Desktop/haloApp/src/app.js:28:20)
在Module._compile(module.js:409:26)
在Object.Module._extensions..js (module.js:416:10)
at Module.load(module.js:343:32)
at Function.Module._load(module.js:300:12)
at Function.Module.runMain(module.js:441:10)
在启动时(node.js:139:18)
在node.js:968:3
var Firebase = require(firebase);



这是我的app.js文件:

 use-strict

var express = require(express);
//依赖项
var request = require(request);
var Options = require(./ router.js)
var app = express();
var bodyParser = require(body-parser);
var Firebase = 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:[我的客户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
}

});

var dbReference = new Firebase(https://haloapp-5cfe2.firebaseio.com/);

另外这里是我的package.json文件,只不过是incase:

$ b $ name $ b $ name $ b $ version $ b $ name $ b $ description $ ,
main:index.js,
scripts:{
test:echo \错误:未指定测试&&退出1

author:,
license:ISC,
dependencies:{
body-parser :^ 1.15.1,
express:^ 4.13.4,
firebase:^ 3.0.5,
nodemon:^ 1.9。 2

}

感谢所有花时间看这个问题又提供了自己的两分钱。非常感谢,让我知道我可以通过提供其他任何东西来帮助你。

解决方案

使用此代码,我能够连接到后台的firebase:

pre $ code $ use $ strict

var express = require(express );
//依赖项
var request = require(request);
var Options = require(./ router.js)
var app = express();
var bodyParser = require(body-parser);
var Firebase = 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:[我的客户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
}

});

//链接到我的firebase数据库
var db = Firebase.database();
//设置对数据库根目录的引用,或者我不太确定的服务器。
var ref = db.ref(/);

这里是一个将数据发送到数据库的示例API调用:

  //当有一个由public / request.js发出的POST请求时,Event Listener 
app.post(/ statSearch,function(req ,res){
//在这种情况下,req是POST请求,请求主体是我随之发送的数据,请参阅request.js
var 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)throw new Error(error);
//这是必须的,因为body是一个字符串,JSON.parse将这个字符串转换为一个对象
var 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);
//在我的数据库中创建一个名为user的孩子
var userRef = ref.child(user);
//成功填充了playerData对象的子对象。
//每次发出新的POST请求时,用户的数据都会重置。
userRef.set(playerData)
});
});

此代码将数据写入我的数据库!

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 turn with information sent from my client makes an api call to this halo api. From there the information given back to me from halo's server is given back to my express server which gives an object back to my client to populate the DOM.

Everything described above I have gotten to work, yay, but now I want o incorporate a firebase database and things are not so perfect. What I want to be able to do is add more functionality with my app. So when that api call is made from my express server (app.js) to halo's server I want to send data to my firebase database instead of back to the client. To me it seems easy in practice to instead take the data object I receive from halo, I'm just calling it halo for now because it's easier, and send it to my firebase database. From there I would use the database to populate the DOM.

As I mentioned earlier, in practice this is proving much more difficult. I need to use firebase in the first place because I need to add CRUD functionality to this app so just not using it is out of the question. currently when running my server I receive this error in the command line after running nodemon src/app.js:

/Users/MMac/Desktop/haloApp/src/app.js:28
var dbReference =  new Firebase("https://haloapp-5cfe2.firebaseio.com/");
                   ^

TypeError: Firebase is not a function
    at Object.<anonymous> (/Users/MMac/Desktop/haloApp/src/app.js:28:20)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)
    at node.js:968:3

Based on this error I'm thinking that I'm not requiring the correct file for firebase but I just don't know which one to include. I installed the node package for firebase and the tutorials I have read just use var Firebase = require("firebase");

This is my app.js file:

"use-strict"

var express = require("express");
//dependencies
var request = require("request");
var Options = require("./router.js")
var app = express();
var bodyParser = require("body-parser");
var Firebase = 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"
}

});

var dbReference =  new Firebase("https://haloapp-5cfe2.firebaseio.com/");

Also here is my package.json file just incase:

{
  "name": "haloapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.15.1",
    "express": "^4.13.4",
    "firebase": "^3.0.5",
    "nodemon": "^1.9.2"
  }
}

I appreciate anyone taking the time to look at this issue and provide their own two cents. Thanks a lot and let me know how I can help you by providing anything else.

解决方案

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

"use-strict"

var express = require("express");
//dependencies
var request = require("request");
var Options = require("./router.js")
var app = express();
var bodyParser = require("body-parser");
var Firebase = 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 database
var 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.js
    var 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) throw new Error(error);
          // This is necessary because the body is a string, and JSON.parse turns said string into an object
          var 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 database
    var 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!

这篇关于无法连接Firebase数据库到Express.js服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆