I am performing an update where, in addition to other data, I need to send Node an array that includes the information of one or more images, but only their path and ID, not the image itself.
I am performing an update where, in addition to other data, I need to send Node an array that includes the information of one or more images to be deleted, but I only pass its path as well as ID, not the image itself since the images are in Cloudinary.
I use formData because among these data I send the new images in case new ones are required, but I receive all the data except for the images to be deleted, since instead of receiving an array I only receive [Object Object] and I cannot work with it. This is my code:
const putProduct = async (productToUpdate, filesToDelete) => {
console.log(filesToDelete) // Array
const formData = new FormData()
const imageArr = Array.from(productToUpdate.pictures)
imageArr.forEach(image => {
formData.append('pictures', image)
})
formData.append('filesToDelete', filesToDelete)
formData.append('barCode', productToUpdate.barCode)
try {
const dataOnLs = localStorage.getItem('cmtjs')
const config = {
headers: {
"Content-Type": "multipart/form-data",
apiKey: dataOnLs
}
}
const { data } = await axiosClient.put(`/products/${productToUpdate.id}`, formData, config )
I receive in Node and go through the console req.body.filesToDelete but it always indicates [Object Object]
let updateProduct = async ( req, res = response ) => {
const filesToDelete = req.body.filesToDelete;
console.log(filesToDelete); // [object Object]
return
CodePudding user response:
FormData requires objects to be strings. Here's the replacements:
Frontend
Replace:
formData.append('filesToDelete', filesToDelete)
With:
formData.append('filesToDelete', JSON.stringify(filesToDelete))
Backend
Replace:
const filesToDelete = req.body.filesToDelete
With:
const filesToDelete = JSON.parse(req.body.filesToDelete)
CodePudding user response:
You should treat the filesToDelete
array the same way you treat productToUpdate.pictures
.
If you want filesToDelete
to appear as an array in req.body.filesToDelete
, use this...
filesToDelete.forEach((f) => {
formData.append("filesToDelete", f);
});
Multer automatically handles repeated fields as an array. You can optionally add []
to the field name for clarity in your code...
formData.append("filesToDelete[]", f);
but the result will be the same.
On the client-side, you can remove the content-type header. Your browser will handle this automatically for you.