I wanted to send the image array and form in react but my problem is it is showing the data in payload but when I debug in backend its body is empty
This is how I am sending data using api
Add a new cafe using multipart/form-data
const api = createAuthAxios()
try {
// Ensure 'form' is a FormData object
if (!(form instanceof FormData)) {
throw new Error('Form data must be a FormData object.')
}
const response = await api.post('/cafes', form)
return response.data // Return the response data directly
} catch (error) {
console.error('Error adding cafe:', error)
throw error // Rethrow error to handle it in the calling function
}
}```
this is my axis setup from where I am trying to create a custom header for the form-data
```const createAuthAxios = () => {
const token = localStorage.getItem('bearerToken')
if (!token) {
na
console.error('No bearer token found')
throw new Error('Bearer token is missing') // Throw error to handle token absence
}
return axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL, // Ensure VITE_API_BASE_URL is properly set in the env files
headers: {
Authorization: `Bearer ${token}`, // Use the token in the Authorization header
},
})
}```
this is my design for react this is how I am creating form data but the problem is it is sending I wanted to send the image array and form in react but my problem is it is showing the data in payload but when I debug in backend its body is empty this error.
"Cannot convert object to primitive value"
this is the error that is being responded and it is completely working on postman
const { register, handleSubmit, setValue, getValues, reset, control } = useForm({
defaultValues: {
name: ”,
location: {
address: {
street: ”,
suburb: ”,
state: ”,
postalCode: ”,
},
},
managedBy: ”,
timetable: [
{ day: ‘Monday’, openingTime: ”, closingTime: ” },
{ day: ‘Tuesday’, openingTime: ”, closingTime: ” },
{ day: ‘Wednesday’, openingTime: ”, closingTime: ” },
{ day: ‘Thursday’, openingTime: ”, closingTime: ” },
{ day: ‘Friday’, openingTime: ”, closingTime: ” },
{ day: ‘Saturday’, openingTime: ”, closingTime: ” },
{ day: ‘Sunday’, openingTime: ”, closingTime: ” },
],
images: [],
},
})
const { fields } = useFieldArray({
control,
name: ‘timetable’,
})
const [imagePreviews, setImagePreviews] = useState([])
const [users, setUsers] = useState([])
const submitForm = async (data) => {
try {
// Create FormData object
const formData = new FormData()
// Append basic fields to FormData
formData.append('name', data.name)
formData.append('location[address][street]', data.location.address.street)
formData.append('location[address][suburb]', data.location.address.suburb)
formData.append('location[address][state]', data.location.address.state)
formData.append('location[address][postalCode]', data.location.address.postalCode)
formData.append('managedBy', data.managedBy)
// Append timetable fields to FormData
data.timetable.forEach((timetableItem, index) => {
formData.append(`timetable[${index}][day]`, timetableItem.day)
formData.append(`timetable[${index}][openingTime]`, timetableItem.openingTime)
formData.append(`timetable[${index}][closingTime]`, timetableItem.closingTime)
})
// Append images (files) to FormData
data.images.forEach((file) => {
formData.append('images', file)
})
// Send FormData to the API
const response = await add_cafe(formData)
console.log('Cafe added successfully:', response.data)
// Reset the form and clear previews on success
reset()
setImagePreviews([])
} catch (error) {
console.error('Error submitting cafe:', error)
}
}
2
Answers
Usually when encountering this issue, it’s because I forgot to include the
body-parser
lib:You can read more here about how it works.
Express has no built-in middleware to handle multipart/form-data, therefore the middleware multer may be a choice.
The following sample code shows its usage.
The sample is a node server. The testing code is also written in the server, just inside app.listen method.
The way in which you have populated the formData object would remain the same. When multer is used, you would get the same data in the server as well. The req.body and the req.files are the two objects you would be able to refer for that. The sample code also shows the same with some dummy data.
Please also note that the image files will be uploaded into the folder in the server as soon as the middleware has been run.
server.js
Test run
node server.js
Server console logs