Reputation: 3327
I have a submit form in my react.js front ned, where i use filepond, to get the files, i don't figured a good way to send the files, was to use form data, to send the files.
fileItems.forEach((item, i) => {
console.log(typeof item.file)
const json = JSON.stringify(item.file);
const blob = new Blob([json], {
type: 'application/json'
});
const data = new FormData();
data.append("document", blob)
fileObjects.push({
name: item.file.name,
data: data
});
});
this.setState({fileObjects});
when I log the fileObjects I get this result
But when I log the output in my node.js backend the data is just an empty object.
result: [ { name: 'Udklip.PNG', data: {} } ] }
[ [ { name: 'Udklip.PNG', content: {} } ] ]
i have made a handler to send the request to my node.js backend like such:
onSubmitHandler = (e) =>{
e.preventDefault()
const contactRequest = {
email: this.state.email,
name: this.state.name,
message: this.state.message,
result: this.state.fileObjects
}
const form = axios.post('/api/form', contactRequest)
console.log(contactRequest)
console.log(form)
}
how can i make the POST request to my node.js backend, and parse the files properly?
Upvotes: 0
Views: 1530
Reputation: 1
I had the same problem using multer. But, then I had to add them as middleware since it handles multipart/form-data. Without it, you can't work with form data in backend.
import multer from 'multer'
var multer_middleware= multer()
router.post("/signup", multer_middleware, signup);
Without multer, you can't work with form data and I suggest to use multer, since it has good methods to handle files.
Upvotes: 0
Reputation: 3596
This entry in MDN shows how to add files objects to FormData
A FilePond file item has a file
property which is the actual file.
var file = item.file;
var myFormData = new FormData();
myFormData.append('document', file, file.name);
Now you can send the form data to Axios:
axios({
method: 'post',
url: '/api/form',
data: myFormData
});
Upvotes: 1