On my frontend application, I have a form where a user can upload a file. I want to upload this file to my Node.js backend using the fetch
API.
Frontend code
HTML:
<form id="forecast-form">
<input type="file" id="csvFile" />
<input type="submit" value="Submit" />
</form>
JavaScript:
const handleSubmit = (e) => {
e.preventDefault();
const csv = e.target.csvFile.files[0];
console.log(csv); // This actually logs the file object
const formData = new FormData();
formData.append('csvFile', csv);
const options = {
method: 'POST',
body: formData,
};
fetch('http://localhost:4000/api/v1/forecast', options)
.then((res) => res.text())
.then((data) => console.log(data)); // output: {}
}
Node.js + express code
create: async (req, res, next) => {
try {
const body = req.body;
console.log(body); // output: {}
res.status(201).send(body);
next();
} catch (err) {
next(err);
}
}
But the only output I get, both from the frontend and backend, is an empty object {}.
Edit: I wouldn't say this question is a duplicate since the aforementioned question in mind is not specific to the fetch API, which this question is.