skip to Main Content

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?

2

Answers


  1. 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

    Login or Signup to reply.
  2. Other solution would be to downgrade node.js in case u don’t want to add multer just for this.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search