0

I have a Google Cloud Function based on node.js 8 and I'd like to process the body of the IncomingMessage object. I can't access the body via req.body as lined out in the Google Examples. I get req.body is undefined.

If I log the req object, I get an IncomingMessage object, hence I try to read the body as explained here and I end up with the following implementation.

'use strict';

exports.insertSuccessfulConsent = (req, res) => {
    console.log(`METHOD: ${req.method}`);
    console.log(`HEADERS: ${JSON.stringify(req.headers)}`);

    let body = "";

    req.on('data', chunk => {
        body += chunk.toString(); 
    });

    req.on('end', () => {
        console.log(body);
    });

    console.log('Body: ' + body); 


    let message = 'POST processed';
    res.status(200).send(message);
};

Unfortunately the body is empty, although the HTTP POST request has data in the body. This is my test call:

curl -X POST HTTP_TRIGGER_ENDPOINT -H "Content-Type:application/json" -d '{"name":"Jane"}'

Headers and HTTP Methods are correct in the log, only the body is missing.

Question is: How to I get the Body from the req object?

geri-m
  • 665
  • 2
  • 11
  • 23

1 Answers1

1

I'm not sure but in the example written by Google they are referencing Express and you referenced a solution for an issue with NodeJS plain http module. I'm not sure if it fits here, despite that being used by express itself.

Is your listener for the 'data' event even being called? If not, that's the reason why your body is empty, you defined it as empty before and your listener never got called by the data event.

The reason why your req.data is set as undefined is probably because it is undefined by default in Express. You will need a parser as express points out on its documentation.

You can use something like body-parser module for populating your req.body.

I hope it helps.