简体   繁体   中英

How can I view the body data of an HTTP request in a Firebase Functions JS?

"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: 在此处输入图像描述

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM