How to get body form data from post req in express?

34 Views Asked by At

I have an express project and I send data from Postman. The data consists of text, numbers, and image files

from postman

Images are handled well and are uploaded and controlled The problem is that I cannot find the text data in req.body I use multer to control the images And also use bodyParser

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

Below is the code with which I execute the commands

products.post('/addProduct', (req, res) => {
    const newProduct = new productModel({
        name: req.body.name,
        price: req.body.price
    });
    const productId = newProduct._id;


    const storage = multer.diskStorage({
        destination: function (req, file, cb) {
            const destinationFolder = `./store/productsImg/${productId}`;
            
            if (!fs.existsSync(destinationFolder)) {
                fs.mkdirSync(destinationFolder);
            }
            
            cb(null, destinationFolder);
        },
        filename: function (req, file, cb) {
            const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
            cb(null, file.fieldname + '-' + uniqueSuffix + file.originalname);
        }
    });
    
    const upload = multer({ storage: storage }).array('imgs');
    
    upload(req, res, function (err) {
        if (err) {
            console.error(err);
            return res.status(500).json({ error: 'An error has been detected' });
        }
        
        
    });
})

The problem here is when I ask to extract data from req.body.name or req.body.price it comes back to me undefind

I tried many things, the most important of which is that I tried changing the content-type several times, but I was getting one of two things: either images, and I was losing texts or vice versa.

0

There are 0 best solutions below