Thursday 15 March 2018

How can I send a JSON object which also has a File object through a POST request?

I posted a StackOverflow question about it.But basically, I have an object like this:const people = { admin: { adminName: 'john', avatar: { img: File } }, moderator: { modName: 'jake', avatar: { img: File } } }; The img property is just a File object. I'm basically trying to send this object to my Node server in a POST request.Here is what I tried:client.jslet formData = new FormData(); formData.append('admin-name', people.admin.adminName); formData.append('admin-avatar', people.admin.avatar.img); formData.append('moderator-name', people.moderator.modName); formData.append('moderator-avatar', people.moderator.avatar.img); fetch('/submit', { method: 'POST', body: formData }) server.jsimport formidable from 'express-formidable'; router.use('/submit', formidable()); router.post('/submit', (req, res) => { console.log(req.files); // This contains the Files objects console.log(req.fields); // This has the rest of the data res.end(); }); Server Output{ 'admin-avatar': File {}, 'moderator-avatar': File {} } { 'admin-name': 'john', 'moderator-name': 'jake' } The problem with this approach is that I have to manually append each field, which isn't really feasible for a larger object. Also, I'm not crazy about the fact that the admin values are not grouped together anymore in the server-side, as well as the moderator values.Is there a better way to do this?

Submitted March 15, 2018 at 11:12AM by inhwjs

No comments:

Post a Comment