提问者:小点点

从云函数内部的请求体访问单个字段


我正在向一个云函数发送post请求,该函数包含以下主体:

{message: "this is the message"}

如果我尝试打印整个请求正文,它会显示它,但是如果我尝试获取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")
});

共1个答案

匿名用户

我个人以前没有使用过firebase,但是从您的代码和req.body打印主体这一事实来看,您可能需要将request-body解析为json,以便能够访问message属性:

const body = JSON.parse(req.body);
console.log(body.message);

您还可能需要为JSON内容设置一个bodyparser。在一个普通的express-app中,您可以使用(注意,您不再需要使用bodyparser从上面手动解析):

const bodyParser = require('body-parser');
app.use(bodyParser.json();