I have a controller which is to create a product. The request must contain the image also. So, I am using Postman form data to pass in the values. But I am not able to get the values at all. The req.body is always undefined. How to overcome this?
app.js
import express from "express";
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use("/products", router);
router.js
import { Router } from "express";
const router = Router()
productRouter.post("/add", newproduct)
export default router;
product.controller.js
const newproduct = (req, res) => {
try {
console.log('body', req.body)
// just for the sake i am explicitly returning some response
res.status(201).json({ message: "Product created successfully" });
} catch (error) {
res.status(500).json(error)
}
};
Getting an empty object like
I am using the form data tab only because of the file upload. It is not included in the Postman screenshot (failed to attach), but that is why I am using the form data tab to send the request. I followed Express + Postman, req.body is empty, Req.body is empty in express even i did everything, Request body is empty when posting form-data. All are mainly telling to make it raw and select json and the actual solutions also resulted in empty object only. What am I doing wrong?