I've working on an Express 3.x API server (don't ask why I'm not upgrading to 4.x; I'm not in control of that), and I'm trying to implement support for batch requests for a particular endpoint. The endpoint currently supports regular requests (takes a JSON object), but I want it to also be able to take array of JSON objects, e.g.:
POST /api/posts
Body:
[
{ "title": "Hello World", "text": "blah blah" },
{ "title": "Hello World 2", "text": "blah blah blah" }
]
When I try to access the body of the request for a single request using req.body
, I can retrieve the data just fine (it's just a regular JSON object). However, when I send an array, I find that the data gets parsed as an object of objects(?) instead of an array.
req.body = { "title": "Hello World", "text": "blah blah" };
typeof req.body;
// object
req.body.toString();
// [object Object]
req.body = [
{ "title": "Hello World", "text": "blah blah" },
{ "title": "Hello World 2", "text": "blah blah blah" }
];
typeof req.body;
// object
req.body.toString();
// [object Object],[object Object]
I tried using a simple check like this:
if (req.body.toString() !== '[object Object]') {
But an array containing only one object breaks this. E.g.:
req.body = [{ "title": "Hello World", "text": "blah blah" }];
typeof req.body;
// object
req.body.toString();
// [object Object]
Given this, is there guaranteed way to check to see if my data is an array?
The typical way to do this in any JavaScript environment would be:
if ( req.body instanceof Array ) {
// do stuff
}
But since you have the luxury of your JavaScript running inside of V8, you could also use the following without any issues:
if ( Array.isArray(req.body) ) {
// do stuff
}
Just personal preference on which one you use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With