2017-04-12 49 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');