I am trying to debug this ReactJS code where no matter what I try the backend doesn't receive any data in the body and the file is undefined. I checked by printing all the data(user and element.files[0]) till the line just before the axios request and all seems to be working fine.
Just when the request reaches backend, data doesn't show.
Partial js code:
async function updateAvatar(element) {
let data = new FormData();
// `user` is an object that exists as a state
data.append('user', user);
data.append('file', element.files[0])
const response = await axios.post(`http://localhost:3001/user/upload_avatar`, data, {
headers: { "Content-Type": "multipart/form-data" }
});
}
Partial HTML code:
<label htmlFor='update-avatar'><span className='btn btn-outline-primary'>Update</span></label>
<input id='update-avatar' type={'file'} className='custom-file-upload' onChange={e => updateAvatar(e.target)} />
The code was working till yesterday and is not sending data properly since today.
Does anyone see any issues with the code?
The solution was really really simple. I had difference in variable name(user) in the frontend FormData() and the backend multer code(user_name). This was causing the issue. By changing the variable name in multer to user, the request works fine.