I am trying to send an array of type String and a png file using multipart/form data. I receive my image file and I receive my data via req.body. However the array is of type String, as expected. How do I parse this into an array?
2 Answers
You could use JSON.parse to convert string to array.
let tattooGroups= `["Women", "Unisex"]`;
console.log("Without JSON.parse -> ", typeof tattooGroups);
console.log("With JSON.parse -> ", typeof JSON.parse(tattooGroups));
console.log("With JSON.parse, Is Array -> ", Array.isArray(JSON.parse(tattooGroups)));
console.log(JSON.parse(tattooGroups));
Comments
The main problem I see with passing the tatoogroups field as a string to be parsed in a second step is inconsistency and unnecessary complexity on the application parsing code.
I know this is an old question, but I've searched for something similar recently and found no solution, so I've released a (MIT licensed) middleware to solve this problem: https://github.com/hugoaboud/express-multibody.
You can install it with:
npm i express-multibody
Then import and use it on the express app:
import multibody from 'express-multibody';
app.use(multibody())
It allows you to send your data as:
name=Anchor_001
tattoogroups[]=Women
tattoogroups[]=Unisex
tattooimage={binary}
And receive it on the req.body as:
{
name: 'Anchor_001',
tattoogroups: ['Women', 'Unisex'],
tatooimage: {
filepath: '.../project/tmp/random-uuid-generated-by-multibody',
delete()
}
}
The documentation has a few more examples of more complex data that can be parsed.

