教程文档中的简单火碱云函数 "could not handle request"



遵循官方Firebase云函数教程(https://firebase.google.com/docs/functions/get-started(,在尝试实际部署和使用该功能时遇到错误(https://firebase.google.com/docs/functions/get-started#deploy-and-execute-addmessage(。成功完成示例函数的部署并指示"在 addMessage(( URL 中添加文本查询参数,并在浏览器中打开它"后,结果是文本

错误:无法处理请求

显示在浏览器中。在浏览器中检查开发人员控制台,我看到

无法加载资源:服务器以状态 500 (( 响应

(实际上不知道如何解释这一点(并查看Firebase仪表板中的使用情况统计信息,可以看到该功能正在激活(只是工作不顺利(。用于部署的确切代码如下所示

//import * as functions from 'firebase-functions';
// // Start writing Firebase Functions
// // https://firebase.google.com/docs/functions/typescript
//
// export const helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();

// 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.
return admin.firestore().ref('/messages').push({original: original})
.then((snapshot) => {
// Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
return res.redirect(303, snapshot.ref.toString());
});
});

以前从未使用过谷歌云功能,任何调试信息或解决方案都可能出现这里的问题将不胜感激。

最终,

希望最终使用云函数与firestoreDB一起使用,而官方教程似乎旨在与firebaseDB一起使用。因此,如果在这方面需要做出任何特别的改变,也将不胜感激。

代码中的以下行是错误的:

return admin.firestore().ref('/messages').push({original: original}).then()

您正在"混合"实时数据库和Firestore,它们应该以不同的方式进行查询(即写入,读取,删除(,因为它们的数据模型不同,请参阅 https://firebase.google.com/docs/firestore/rtdb-vs-firestore。特别是,虽然"实时数据库和Cloud Firestore都是NoSQL数据库",但前者"将数据存储为一个大型JSON树",而后者"将数据存储在集合中组织的文档中"。

事实上,您引用的"入门"帮助项中的原始代码以实时数据库为目标,admin.database()

return admin.database().ref('/messages').push({original: original}).then()

在这一行代码中,按firestore()替换database()是行不通的。

您应该查看Firestore文档,例如,此处,此处和此处,以了解如何写入Firestore。

例如,您可以按如下方式修改云函数:

exports.addMessage = functions.https.onRequest((req, res) => {
// Grab the text parameter.
const original = req.query.text;
admin.firestore().collection("mydocs").doc("firstdoc").set({original: original})
.then(() => {
console.log("Document successfully written!");
res.send({original: original});  //Just an example, as there is not that much interest to send back the value of original...  
})
.catch(error => {
console.error("Error writing document: ", error);
res.status(500).send(error);
});
})

最后,我建议您观看以下官方视频系列"Learning Cloud Functions for Firebase"(此处(,特别是标题为"Learn JavaScript Promises"的三个视频。您将特别注意到,对于 HTTP 触发的函数,您应该只发送响应,而不使用return

相关内容

最新更新