When I send data using postman the Title,description and image I am sending goes through.
This is my post array:
router.post('/', uploadS3.array('meme',3),(req, res, next)=>{
// res.json(req.file.location)
console.log(`req.files =================${req.headers}`);
// console.log("req.file.location===",req.file.location, "req.body===",req.body);
const locationURL = req.files.map(item=>item.location);
//Send image alongside with other form fields
postModel.create({...req.body,image:locationURL}, (error, returnedDocuments) => {
if (error) return next(error);
res.json(returnedDocuments);
})
})
When I try to send data using my front end, it does not go to the backend properly, the response I recieve is nothing if I do not include an image, and the title and description is not being passed.... notice that my postModel expects the title and description to be inside of req.body
postModel.create({...req.body,image:locationURL}
I am sending the data by appending it to the FormData() object
Just to be clear, setFiles is the setter for file const [file, setFiles] = useState({ selectedFile: null, loaded: 0 });
const onChangeFile = event => {
if (maxSelectFile(event) && checkMimeType(event) && checkFileSize(event)) {
setFiles({
selectedFile: event.target.files
});
}
console.log(event.target.files)
}
const submitFormHandle = event => {
const data = new FormData();
for (let i = 0; i < file.selectedFile.length; i++) {
data.append("meme", file.selectedFile[i]);
}
data.append("title", title);
data.append("description", description);
axios
.post("http://localhost:3200/api/posts/", data)
.then(res => {
toast.success('upload success')
})
.catch(err => {
toast.error('upload fail')
})
}
You can post axios data by using FormData
using below approach :
For the field try using set
on FormData
object and for image use append
like this.
Change your code to:
data.set("title", title);
data.set("description", description);
Kindly let me know if this doesn't work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.