skip to Main Content

"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?

Request :
enter image description here

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


  1. req.body can be used if the request body type is application/json or application/x-www-form-urlencoded otherwise use req.rawBody

    Login or Signup to reply.
  2. 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 on Content 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 using JSON.parse(req.body); to parse the request body.
    So the updated code will something look like:

    exports.test = functions.https.onRequest(async (req, res) => {
      const body = JSON.parse(req.body);
      const id = body.id;
      // ...
    });
    

    OR

    You can use the body parser middleware and force parse the body as JSON as shown in this answer

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search