Access individual fields from request body inside cloud function

Viewed 1348

I'm sending a post request to a cloud function which contains the following body:

{message: "this is the message"}

If I try to print the entire body of the request, it shows it, but if I try to get the message field, I get undefined in the console.

Here's my function:

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")
});
3 Answers

You don't need a body parser for Cloud Functions as described in the other answer here. Cloud Functions will automatically parse JSON and put the parsed JSON object in the body attribute. If you want this to happen automatically, you should set the content type of the request to "application/json" as described in the linked documentation. Then you can use req.body as you'd expect.

I personally haven't worked with firebase before, but from your code and the fact that req.body prints the body, it seems that you probably need to parse the request-body as json in order to be able to access the message property:

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

It could also be the case that you need to setup a bodyparser for json content. In a normal express-app you can do this using (note that you don't need the manual parsing from above anymore using bodyparser):

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

EDIT: see Doug's answer for the correct way to do this, i.e. to fix your request and set the content-type to application/json in order for Cloud Functions to automatically parse and populate req.body with the request body.

You need to just convert the request body into a JSON object in cloud function.

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