2017-04-12 96 views
2

我正在尝试使用NodeJS设置firebase JS客户端。到目前为止,这里是我的代码无法让节点JS应用程序中的Firebase运行

var firebase = require('firebase/app'); 

require('firebase/database'); 

var config = { 
    apiKey: "MY_SECRET_KEY_fhcWICPI", 
    authDomain: "my_fir_app.firebaseapp.com", 
    databaseURL: "https://my_fir_app.firebaseio.com", 
}; 
var firApp = firebase.initializeApp(config); 

firebase.database.enableLogging(true) 

// Get a reference to the database service 
var database = firebase.database(); 

然后,这里是我的Firebase函数之一,用于将数据保存到实时数据库。

/** 
* This will save the authors of stories in Firebase 
* @param {String} id    The ID of the author 
* @param {String} firstName  The authors first name 
* @param {String} lastName  The authors last name 
* @param {Timestamp} dateCreated The unix time stamp when the author was created 
*/ 
function saveStoryAuthor(id, firstName, lastName, dateCreated) { 
    database.ref('mystoriesdb/authors/' + id).set({ 
     first_name: firstName, 
     last_name: lastName, 
     date_created : dateCreated 
    }); 
} 

最后,在什么地方我的代码中间我调用这个函数作为

... 

saveStoryAuthor('MZ8XWXNrkG', 'Dennis', 'Richie') 

... 

但是,这是我在日志中获取的(因为我已经启用了日志记录)

$ node index.js 
p:0: Browser went online. 
p:0: Making a connection attempt 
getToken() completed. Creating connection. 
c:0:0: Connection created 
p:0: Failed to get token: Error: No transports available 
p:0: data client disconnected 
p:0: Trying to reconnect in 326.9669258513522ms 
0: onDisconnectEvents 
p:0: Making a connection attempt 
getToken() completed. Creating connection. 
c:0:1: Connection created 
p:0: Failed to get token: Error: No transports available 

我可能做错了什么。有人可以帮忙吗?

+0

我得到了同样的问题。你有没有机会解决这个问题? – rmmmp

+0

是的,下面提供的答案适用于我。我刚接受它。 – nmvictor

回答

1

看来你还没有为了增加火力将项目与节点JS

退房文档here创建的服务帐户。

var admin = require("firebase-admin"); 

var serviceAccount = require("path/to/serviceAccountKey.json"); 

admin.initializeApp({ 
    credential: admin.credential.cert(serviceAccount), 
    databaseURL: "https://<DATABASE_NAME>.firebaseio.com" 
}); 
+0

[文档](https://firebase.google.com/docs/web/setup#add_firebase_to_your_app)表示,如果您想拥有特权环境(例如服务器),则只能使用Firebase管理员。 Node.js可以通过桌面或物联网应用程序成为最终用户。 – rmmmp

1

您需要更改

var firebase = require('firebase/app'); 

var firebase = require('firebase');