I am trying to send FormData from my react front-end to my express backend. The formdata contains some key:value pairs for registration and an Image file, The problem is that the server isn't able to pick up the formdata at all, The req.body is just and empty object and due to that the upload isn't working as well. I tried logging the formdata in the frontend and the formdata is fine, it does contains the values and the file but it doesn't reach the server.
My function code from where I am sending the request.
const handleFormSubmit = async (values, action, acceptedFile) => {
// action.resetForm()
// here values = {
// name:"Some name",
// email:"some@gmail.com",
// password:"password",
// confirm_password:"confirmed_pass"
// }
const formData = new FormData()
Object.keys(values).map(key=>{
formData.append(key, values[key])
})
formData.append('picture', acceptedFile)
const raw = await fetch("https://6025-103-79-250-41.ngrok-free.app/check",{
method:"POST",
headers:{
"Content-Type":"multipart/form-data"
},
body:formData
})
const data = await raw.json()
console.log(data)
}
I am using ngrok for port forwarding. Form data here is fine, I logged it and checked it, It contains the file and the values. I am using react-dropzone to get the file and the dropzone exists in a .
My express server code
const express = require('express')
const multer = require('multer')
const cors = require('cors')
const bodyParser = require('body-parser')
const app = express()
app.use(cors())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
const storage = multer.diskStorage({
destination: (req, file, cb)=> {
cb(null, 'Images/')
},
filename: (req, file, cb)=> {
cb(null, Date.now() + "_" + file.originalname)
}
})
const uploadMiddleWare = multer({ storage: storage })
app.post("/check", uploadMiddleWare.single('picture'), (req, res)=>{
console.log(req.body)
// req.body logs as an empty object {}
res.status(200).json(req.body)
})
app.listen(3001,()=>{
console.log("Server started")
})