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?