I am trying to POST a file from a front-end index.html to an Express Server running in the background. The API is then supposed to save the file into Firebase Storage. The server is running properly and it is receiving the POST, but there is no data in the req.body.
index.html - Front-end
<form method="POST" id="form">
<input type="file" id="file" name="file" multiple>
<input type="submit">
</form>
<script>
const form = document.querySelector('#form')
const postFile = (e) => {
e.preventDefault()
const header = { "Content-Type": "multipart/form-data" }
let formData = new FormData()
formData.append('file', this.file.files[0])
fetch('http://localhost:3003/file', {
method: form.method,
headers: header,
body: formData
}).then(() => {
alert("OK")
}).catch(() => {
alert("Nope")
})
}
form.addEventListener('submit', (e) => postFile(e))
</script>
server.js - Back-end (Incomplete)
const server = express()
const routes = require('./routes')
server.use(cors())
server.use(express.urlencoded({
limit: '50mb',
extended: true
}))
server.use(express.json({
limit: '50mb',
extended: true
}))
server.use(routes)
server.listen(3003)
fileController.js - Back-end (Incomplete)
exports.addFile = async (req, res) => {
try {
console.log(req.body)
return res.status(200).send({
message: "Ok"
})
} catch (e) {
return res.status(500).send({
message: e.message
})
}
When I console.log(this.file.files[0]) before fetching it actually returns the File as it is supposed to, but in the server is just an empty array. Front-end console.log; Server console.log