"I’m trying to view the body data in a Firebase Functions POST request, but the console always returns "undefined" in the Firebase function logs!
Question: How can I view the body data in a Firebase function to use it?
Here My Code :
exports.test = functions.https.onRequest(async (req, res) => {
const id = req.body.id
});
I allready used but not working :
req.on('data', (chunk) => {
// The chunk is a Buffer object containing a chunk of the request body data
body += chunk;
}).on('end', () => {
// The request body data has been fully received, and the `body` variable contains the complete request body
});
i should to get id from body.id
2
Answers
req.body can be used if the request body type is application/json or application/x-www-form-urlencoded otherwise use req.rawBody
As per this thread’s answer you should use
Content-Type
and make it to "application/json"as only then your body will be accessible like as shown in here
Also you can check out Read values from the request which explains the need of
application/json
onContent Type
.If you check the firebase functions logs you can see there is no incoming body received from the request and because of that your body content’s are undefined.
There is also a possibility that the
req.body
property in a Firebase Functions is not properly formatted or if it is not properly parsed by the Function, so you can force it to parse usingJSON.parse(req.body);
to parse the request body.So the updated code will something look like:
OR