Home > OS >  req.body undefined in postman form-data but able to get in raw json
req.body undefined in postman form-data but able to get in raw json

Time:09-14

app.js

const express = require('express');
const app = express();
const hostname = '127.0.0.1';
const port = 3000;
const path = require('path');

const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

app.use('/products', require('./Routes/products.js'));

// Set EJS as templating engine 
app.set("view engine", "ejs");

app.listen(port, () => {
  console.log(`Listening to http://${hostname}:${port}`);
});

module.exports = app;

product.js

const express = require('express');
const router = express.Router();
const path = require('path');
const Product = require('../Models/product.js')

// Post
router.post('/', async (req, res) => {
    console.log('req.b: ', req.body);
    const product = new Product ({
        name: req.body.name,
        theme: req.body.theme,
        price: req.body.price,
        size: req.body.size,
        amount: req.body.amount
    });
    try {
        const savedProduct = await product.save();
        res.json(savedProduct);
    }catch (err) {
        res.json({ message:err })
    }
})

I'm getting a undefined req.body when i try to send data on postman using body form-data and i'm able to get it when I use raw json only. Am I missing something which doesn't allow me to get the form data?

CodePudding user response:

after the current update of node form-data has been removed from the nodejs now if you want get data from formdata you have to use multer then only you will be able to get data in req.body

CodePudding user response:

Other solution would be to downgrade node.js in case u don't want to add multer just for this.

  • Related