Uploading a file using "fetch" in reactjs
I am trying to upload a file using ReactJS.
handleUploadfile = (event) => {
event.preventDefault();
const data = new FormData();
data.append('photo',event.target.files[0] );
data.append('name', 'Test Name');
data.append('desc', 'Test description');
fetch("http://localhost:3001/todo/upload", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: data
}).then((response) => {
return response.text();
})
}
For some reason I am not able read the files at nodejs(+multer) server using:
req.files
which shows "undefined" at post router.
Finally I found the solution
I had to remove the 'Content-Type' from headers section and it worked out in nodejs using multer.
Using the "multipart/form-data"
'Content-Type': 'multipart/form-data'
requires us to set boundaries and hence it is throwing error at nodejs "Error: Multipart: Boundary not found"
Using the "application/x-www-form-urlencoded"
'Content-Type': 'application/x-www-form-urlencoded'
I am getting the req.body filled but as string but not able to access the individual values.
Hence final solution is removal of 'Content-Type'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With