multipart/form-data returns empty object | Nodejs

3k views Asked by At

Form with POST method and enctype="multipart/form-data" returns empty object in Nodejs Express.

In app.js I have used:

const app = express()
app.use(express.urlencoded({ extended: true }))
app.use(express.json())

While using only POST type and action in the <form> tag

req.body gives output in json smoothly and have no issues.

But using enctype="multipart/form-data" in express req.body returns { } - empty object

Can anyone help with this?

2

There are 2 answers

2
cbr On

The urlencoded middleware only handles the application/x-www-form-urlencoded content type and json handles the application/json content type. If you specifically need to use multipart/form-data (e.g. if you need to handle file uploads), you'll need a package for that, since as of writing, express doesn't come with a multipart parser out of the box. Common packages used to handle multipart are multer and formidable.

Alternatively, if you don't need to upload files or other binary content, just remove the enctype attribute as <form> defaults to application/x-www-form-urlencoded.

0
Smith July On

incase your using multer, its possible that your calling the upload method last, please call the upload that checks for image and then the other data from the form can later be submitted

i will give an example of my route

router.post('/add-product',productController.isUserAllowed,upload.single('avatar'), productController.add_product);

so initally i was calling productController.add_product beforeupload.single('avatar'), and it didnt work, till i started with the upload that checked the image , then the add_product