Actually i am sending a Form Data Which contains input text and input Files I am doing it like This but i am getting an empty object in response
Here is my Code
const [ModelInfo,setModelInfo] = useState({
title:"",
description:"",
category:""
})
const [Modelfile,setModelfile] = useState({
file1:"",
file3:"",
file4:""
})
Here Is My Fuction To Handle Submit
e.preventDefault();
const formData = new FormData();
// My Post Files Object
for(let key in Modelfile){
formData.append(key,Modelfile[key][0])
}
// My Post Text Object
for(let key in ModelInfo){
formData.append(key,ModelInfo[key])
}
fetch("http://192.168.10.8:8300/createpost",{
method:"POST",
body:formData
})
.then((resp)=>{
resp.json().then((data) => {
console.log(data)
})
})
Payload :
file1: (binary)
file3: (binary)
file4: (binary)
title: test
description: test
category: test
Preview : {}
Getting Empty Obj in response
There are some possibilities that may cause the issue:
Your headers are not set properly. Set Content-Type header to multipart/form-data or application/x-www-form-urlencoded when sending your data.
On your server, you don't have body-parser or multer library. You should use this libraries (not together) in order to access your req.body and parse it.
Maybe you forgot to add this config (in your index file in the root directory of the server):
app.use(express.urlencoded({
extended: true
}))
As a note, you can access your files with req.files in server and other fields with req.body.