我想用云功能进行一些测试,以实现更大的目标。作为一名Android开发人员,我的知识在JavaScript方面有点受限。
我正在尝试使用Cloud功能从firebase访问此数据库。
我的代码访问此数据库以在浏览器中获取JSON
响应。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const cors = require('cors')({origin: true});
// Take the text parameter passed to this HTTP endpoint and insert it into the
// Realtime Database under the path /messages/:pushId/original
exports.addMessage = functions.https.onRequest((req, res) => {
// Grab the text parameter.
const original = req.query.text;
// Push the new message into the Realtime Database using the Firebase Admin SDK.
admin.database().ref('/messages').push({original: original}).then(snapshot => {
// Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
res.redirect(303, snapshot.ref);
});
});
// Listens for new messages added to /messages/:pushId/original and creates an
// uppercase version of the message to /messages/:pushId/uppercase
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
.onWrite(event => {
// Grab the current value of what was written to the Realtime Database.
const original = event.data.val();
console.log('Uppercasing', event.params.pushId, original);
const uppercase = original.toUpperCase();
// You must return a Promise when performing asynchronous tasks inside a Functions such as
// writing to the Firebase Realtime Database.
// Setting an "uppercase" sibling in the Realtime Database returns a Promise.
return event.data.ref.parent.child('uppercase').set(uppercase);
});
var db = admin.database();
exports.getUserMessage = functions.https.onRequest((req, res) => {
var query = firebase.database().ref("messages").orderByKey();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
// key will be "ada" the first time and "alan" the second time
var key = childSnapshot.key;
// childData will be the actual contents of the child
var childData = childSnapshot.val();
});
});
});
但我收到错误:
错误:无法处理请求
这些是来自Firebase的日志错误:
ReferenceError: firebase is not defined
at exports.getUserMessage.functions.https.onRequest (/user_code/index.js:34:49)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:26:47)
at /var/tmp/worker/worker.js:635:7
at /var/tmp/worker/worker.js:619:9
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
package.json脚本
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"dependencies": {
"cors": "^2.8.1",
"firebase-admin": "~4.2.1",
"firebase-functions": "^0.5.7"
},
"private": true
}
答案 0 :(得分:4)
这里的问题是:
var query = firebase.database().ref("messages").orderByKey();
应该是
db.ref("messages").orderByKey();
您在该行中使用的firebase
未在Cloud Functions for Firebase中定义。如果要查询数据库,则已使用Admin SDK对其进行了引用:
var db = admin.database();