我试图修改Firebase函数的Getting Started部分中的简单示例,以读取(POST)请求的主体,而不是所编写的GET请求的参数。
以下是未修改的示例:
// The Cloud Functions for Firebase SDK to create Cloud Functions and triggers.
const {logger} = require("firebase-functions");
const {onRequest} = require("firebase-functions/v2/https");
const {onDocumentCreated} = require("firebase-functions/v2/firestore");
// The Firebase Admin SDK to access Firestore.
const {initializeApp} = require("firebase-admin/app");
const {getFirestore} = require("firebase-admin/firestore");
initializeApp();
// Take the text parameter passed to this HTTP endpoint and insert it into
// Firestore under the path /messages/:documentId/original
exports.addmessage = onRequest(async (req, res) => {
// Grab the text parameter.
const original = req.query.text;
// Push the new message into Firestore using the Firebase Admin SDK.
const writeResult = await getFirestore()
.collection("messages")
.add({original: original});
// Send back a message that we've successfully written the message
res.json({result: `Message with ID: ${writeResult.id} added.`});
});
// Listens for new messages added to /messages/:documentId/original
// and saves an uppercased version of the message
// to /messages/:documentId/uppercase
exports.makeuppercase = onDocumentCreated("/messages/{documentId}", (event) => {
// Grab the current value of what was written to Firestore.
const original = event.data.data().original;
// Access the parameter `{documentId}` with `event.params`
logger.log("Uppercasing", event.params.documentId, original);
const uppercase = original.toUpperCase();
// You must return a Promise when performing
// asynchronous tasks inside a function
// such as writing to Firestore.
// Setting an 'uppercase' field in Firestore document returns a Promise.
return event.data.ref.set({uppercase}, {merge: true});
});
我似乎无法提取请求的正文。它看起来应该很简单,但我已经尝试了.body,.text和.json的各种组合都没有用。按照Fetch API documentation的指示,我无法弄清楚.body()方法给我的是什么,而且.json()是未定义的。
其他堆栈溢出问题似乎表明req.body.data应该可以工作,但它不适合我。
请帮帮我
1条答案
按热度按时间gojuced71#
如果您没有从request获取body,则可能是您在路由中为此服务设置了GET,或者确保您在应用中添加了body-parser。
您可以通过带有请求处理程序的HTTP请求触发函数。这允许您通过以下支持的HTTP方法调用函数:GET、POST、PUT、DELETE和OPTIONS。
请求对象使您能够访问客户端发送的HTTP请求的属性,响应对象使您能够将响应发送回客户端。
在date()函数示例中,该函数测试URL参数和格式值的主体,以设置要使用的日期/时间格式:
更多参考Call functions via HTTP requests