amehta amehta - 1 month ago 6
Node.js Question

How to find the type of content inside req.body?

As per https://developer.mozilla.org/en-US/docs/Web/API/Request/Request the type of body can be of either type:


  1. ArrayBuffer

  2. Blob

  3. formData

  4. JSON

  5. text



Is there a way for the receiving side to know what type it is? The reason I ask is since I am getting a POST message from a 3rd party where the req.body is empty.

console.info("Headers: ", req.headers); // shows headers
console.log("Data: ", req.body); // shows nothing


However, after further inspection, it seems that I need to process the data as follows (since its using ReadableStream):

req.on('data', function (chunk) {
data += chunk;
});

req.on('end', function () {
var messageData = JSON.parse(data);
console.log("Data: ", messageData); //shows data
}

Answer Source

You could do it yourself but most people use express and the Body Parser library to avoid having loads of boilerplate code to do the parsing for them.