My task involves uploading a file along with some metadata on a JSON object using the "fetch" JavaScript native function on the client side and Express with the multer middleware on the server side.
Client Side:
const formData = new FormData()
formData.append('video', video)
formData.append('userId', userId)
formData.append('property', property)
fetch('/api/video', {
method: 'POST',
body: formData
}).then(response => {
console.log(response)
})
Server Side:
const express = require('express')
const multer = require('multer')
const app = express()
app.use(express.urlencoded())
app.use(express.json())
const multerUpload = multer({ dest: './videos' })
const uploadDebugged = multerUpload.single('video')
function debugMulter(req, res) {
uploadDebugged(req, res, (err) => {
console.log(req.body)
console.log('multer error:', err)
})
res.send()
}
app.post('/api/video', debugMulter)
Server Log:
{ video: 'undefined', userId: '5', property: '1' }
multer error: undefined
Even though Multer did not report any errors, the 'video' folder remained empty.
I am looking for a solution using headers in fetch to allow both JSON data and file posting to the server.
EDIT: It finally worked! The video object was empty on the server side, confirming that fetch, FormData, and Multer are functioning correctly.