I have a client application that posts some formData to my node backend. The data coming from the client is initially an object that contains a files property among others. Before posting to the back-end, I convert the object to formData.
// client.js file
const person = {
email: 'johndoe@gmail.com',
age: 19,
files: [File, File, File],
occupation: '',
status: 'active',
}
person.occupation = this.getOccupation(); // getOccupation() is defined somewhere in the file
const formData = new FormData();
Object.entries(person).forEach(([key, value]) => {
if (key === "files") {
for (let i = 0; i < person[key].length; i++) {
formData.append("files", person[key][i]);
}
} else {
formData.append(key, value);
}
});
// The following logs output the correct information so we're good until this point
console.log(formData.getAll("files"));
console.log(formData.get("occupation"));
console.log(formData.get("status"));
this.submitData(formData); // Posts to the backend
The data is posted to a route in the node backend with the multer middleware - uploadFiles().
const submitDataOptions = {
storage: multer.diskStorage({
destination: "./public/uploads/users/files",
filename: function (req, file, cb) {
console.log('Request body');
console.log(req.body);
console.log('Occupation');
console.log(req.body.occupation);
console.log('Status');
console.log(req.body.status);
const ext = file.mimetype.split("/")[1];
const datetimestamp = Date.now();
const fname = `${datetimestamp}.${ext}`;
cb(null, fname);
},
}),
};
uploadFiles() {
return multer(submitDataOptions).array("files");
}
The files get uploaded just fine but when I console.log(req.body), I notice that an object with only the properties email and age is returned. Logging occupation and status returns undefined in either case. The multer documentation says that req.body will contain the text fields if there were any but in this case I cannot find those.
What is the issue here?