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