I have JS object in the following format which i want to send at backend. I have implemented some code but at nodeJs controller it says hotel is undefined. My written code is following:
let hotel = new FormData();
hotel.append('name', data.append);
hotel.append('slug', data.slug);
hotel.append('logo', data.logo);
hotel.append('coverAvatar', data.coverAvatar);
hotel.append('designs', [{ name: `${+new Date()}`, url: localStorage.getItem('initialDesign') }])
hotel.append('products', [...selectedVariants]);
axios.post(`${baseURL}/hotel`, { hotel },{
headers: {
'Authorization': localStorage.getItem('_AUTH_TOKEN'),
'Content-Type': 'multipart/form-data'
}})
.then(response => {
console.log({ response });
})
.catch(err => {
console.log('err', err);
})
I'm using multipart/form-data because logo and coverAvatar are output of <input type='file' />
My data Format
{
"name": "preshan hotel 2",
"logo": {file},
"coverAvatar": {file},
"romms": [{
"name": "tempDesign",
"url": "https://picsum.photos/600/800"
}],
"facilities": [
{ "facilityId": "61ceb3931b1b68fe90827f23", "facilityMappings": ["61ceb39b1b1b68fe90827f2c", "61ceb39b1b1b68fe90827f41"] },
{ "facilityId": "61ceb3ca1b1b68fe90827f47", "facilityMappings": ["61ceb3ca1b1b68fe90827f50","61ceb3ca1b1b68fe90827f58", "61ceb3ca1b1b68fe90827f56"] },
{ "facilityId": "61ceb3e41b1b68fe90827f5d", "facilityMappings": ["61ceb3e41b1b68fe90827f5f"]}
]
}
You should pass your formdata directly instead of passing an object.
In your example it would look like this:
...
axios.post(`${baseURL}/hotel`, hotel,{
...