0

From react app I am converting Json into Form data but when I receive data on the server end

the arrays and objects that I sent become strings

var formdata = new FormData();

for (let i = 0; i < images.length; i++) {
     formdata.append('Images', images[i], images[i].name)
}

formdata.append('City', State.city)
formdata.append('Description', State.description)
formdata.append('Things_to_Pack', JSON.stringify(thingsToPack))
formdata.append('AreaContacts', JSON.stringify(Contacts))

axios.post(`${url}/city/create`, formdata, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then(res => {
            console.log(res);
        }).catch(error => {
            console.log(error)
        });

The data received on the server

City: 'City Name',
Description: 'Description of city',
Things_to_Pack: "["bag","clothes"]"
AreaContacts: "[{"title":"Emergency","contact":"1111"},{"title":"Emergency","contact":"2222"}]"

Expected Output should be

City: 'City Name',
Description: 'Description of city',
Things_to_Pack: ["bag","clothes"]
AreaContacts: [{"title":"Emergency","contact":"1111"},{"title":"Emergency","contact":"2222"}]

How can I change it into proper Json form before saving in database ? I have also tried json.stringify the req.body data but it didn't work

//Post City at this route 
router.post('/create', upload.array('Images', 12), async (req, res) => {
    let imagesArray = [];
    if (req.files) {
        for (let i = 0; i < req.files.length; i++) {
            imagesArray.push(req.files[i].path)
        }
    }
    console.log(req.body, req.files);
    const city = new City({
        City: req.body.City,
        Description: req.body.Description,
        Images: imagesArray,
        Things_to_Pack: req.body.Things_to_Pack,
        AreaContacts: req.body.AreaContacts
    });
1
  • 3
    json is a string notation. Those strings you have are in fact proper JSON form. If you want to convert them back into objects/arrays, you should JSON.parse them. Commented Jun 26, 2020 at 22:07

1 Answer 1

1
Things_to_Pack: JSON.parse(req.body.Things_to_Pack)
AreaContacts: JSON.parse(req.body.AreaContacts)
Sign up to request clarification or add additional context in comments.

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.