2

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?

Here's my postman request:

enter image description here

Here's my console log:

enter image description here

2 Answers 2

1

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));

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.