从云函数内的请求主体访问各个字段

Eig*_*ice 2 node.js firebase google-cloud-functions

我正在向云函数发送一个发布请求,其中包含以下正文:

{message: "this is the message"}
Run Code Online (Sandbox Code Playgroud)

如果我尝试打印请求的整个正文,它会显示它,但如果我尝试获取该message字段,我会进入undefined控制台。

这是我的功能:

exports.myCloudFunction = functions.https.onRequest((req: any, res: any) => {
    console.log(req.body)\\prints the body of the request fine
    console.log(req.body.message)\\prints "undefined"
    cors(req, res, () => {
        const pl = req.body.message;
        console.log(pl);\\prints "undefined"
    });
    return res.send("all done")
});
Run Code Online (Sandbox Code Playgroud)

Dou*_*son 7

您不需要云函数的正文解析器,如此处其他答案中所述。Cloud Functions 会自动解析 JSON并将解析后的 JSON 对象放入body属性中。如果您希望这种情况自动发生,则应将请求的内容类型设置为“application/json”,如链接文档中所述。然后您就可以req.body按照您的预期使用。