0

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?

Postman screenshot

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

console form data

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?

  • Probably a typo, but you write `console.log('body', req.body)` and in the screenshot it's `payload {}`. Shouldn't it be `body {}`? – Konrad Jul 12 '23 at 19:39
  • 1
    No. I just typed the code here as that but in my file it is like that. For just differentiating i did like console.log('payload', req.body) – Jim Parsons Jul 12 '23 at 20:30

1 Answers1

0

To handle file uploads using form data in Express, you'll need to use additional middleware to parse the form data properly. In your case, you can use the multer middleware. First install multer in your project, then update your router like this,

import { Router } from "express"
import multer from "multer"
import { newproduct } from "./product.controller.js"

const router = Router()
const upload = multer()

router.post("/add", upload.none(), newproduct) // Use upload.none() to handle form data

export default router

Nazrul Chowdhury
  • 1,483
  • 1
  • 5
  • 11