如何使用 Node.js 获取和设置数据到 Firebase?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37378050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:15:23  来源:igfitidea点击:

How to get and set data to Firebase with Node.js?

node.jsfirebasefirebase-realtime-database

提问by Lujska

I'm learning Firebase and Node.js. I want get my Tweets from Twitter and send them to Firebase. I have no problem to get tweet from Twitter. My question is how can I send data to Firebase?

我正在学习 Firebase 和 Node.js。我想从 Twitter 获取我的推文并将它们发送到 Firebase。从 Twitter 获取推文没有问题。我的问题是如何将数据发送到 Firebase?

I tried the following code:

我尝试了以下代码:

var firebase = require('firebase');

// Initialize
var app = firebase.initializeApp({
    ServiceAccount: {
       projectId: "******",
       clientEmail: "****@gmail.com",
       privateKey: "-----BEGIN PRIVATE KEY-----\nkey\n-----END PRIVATE KEY-----\n"
    },
   databaseURL: "****.firebaseio.com"
}); 

// Set Sample Data
firebase.database().ref('/').set({
    username: "test",
    email: "[email protected]"
});

And I got the following error on console:

我在控制台上收到以下错误:

 Debugger listening on port 5858
 crypto.js:279
  var ret = this._handle.sign(toBuf(key), null, passphrase);
                         ^

Error: error:0906D064:PEM routines:PEM_read_bio:bad base64 decode
    at Error (native)
    at Sign.sign (crypto.js:279:26)
    at Object.sign (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\node_modules\jsonwebtoken\node_modules\jws\node_modules\jwa\index.js:54:45)
    at Object.jwsSign [as sign] (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\node_modules\jsonwebtoken\node_modules\jws\lib\sign-stream.js:23:24)
    at Object.JWT.sign (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\node_modules\jsonwebtoken\index.js:137:16)
    at authJwt (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\auth-node\auth.js:83:16)
    at fetchAccessToken (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\auth-node\auth.js:96:17)
    at app_.INTERNAL.getToken (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\auth-node\auth.js:196:14)
    at Zb.getToken (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\database-node.js:28:3496)
    at yh (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\database-node.js:195:334)
 Press any key to continue...

Also, this my firebase Rules: {"rules":{".read":true,".write":true}}

另外,这是我的 firebase 规则:{"rules":{".read":true,".write":true}}

回答by Lujska

I solved my problem. I just downloaded serviceAccount json file from Firebase Console and inserted it to my project. The 'Service Account' file contains everything that you need.

我解决了我的问题。我刚刚从 Firebase 控制台下载了 serviceAccount json 文件并将其插入到我的项目中。“服务帐户”文件包含您需要的一切。

var firebase = require('firebase');

firebase.initializeApp({
    databaseURL: 'https://*****.firebaseio.com',
    credential: 'myapp-13ad200fc320.json', //this is file that I downloaded from Firebase Console
});

Then the code below worked nicely.

然后下面的代码运行良好。

firebase.database().ref('/').set({
    username: "test",
    email: "[email protected]"
});

回答by Brandon

This specific syntax/library for service accounts in nodeapps is being deprecated. The new method of reaching firebase on a server (that is, not a consumer app, like IoT or desktop) is the firebase admin sdk.

node不推荐使用应用程序中服务帐户的此特定语法/库。在服务器(即,不是消费者应用程序,如物联网或桌面)上访问 Firebase 的新方法是firebase admin sdk.

Your initialization code should now go:

你的初始化代码现在应该去:

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"
});

You can still manually key in your credentials, but they're now assigned to a diff't property:

您仍然可以手动输入您的凭据,但它们现在已分配给 diff't 属性:

admin.initializeApp({
  credential: admin.credential.cert({
    projectId: "<PROJECT_ID>",
    clientEmail: "foo@<PROJECT_ID>.iam.gserviceaccount.com",
    privateKey: "-----BEGIN PRIVATE KEY-----\n<KEY>\n-----END PRIVATE KEY-----\n"
  }),
  databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});

回答by riverfall

We faced the same problem with AWS Beanstalk. The root cause was because \nwas replaced by \\nin the private key variable.

我们在使用 AWS Beanstalk 时遇到了同样的问题。根本原因是因为在私钥变量中\n被替换了\\n

After adding the replace regexp it was fixed:

添加替换正则​​表达式后,它已修复:

"private_key": process.env.FIREBASE_PRIVATE_KEY.replace(/\n/g, '\n')

Printing the variables into the log could also help isolating the issue.

将变量打印到日志中也有助于隔离问题。