Search code examples
node.jsjsonpostinsomnia

"Cannot read property 'name' of undefined" POST JSON method in Insomnia


I use for testing my project API Insomnia(like a Postman) program and when i use GET methods all going without problems, but POST method return undefined req.body.name and req.body.price, this error which i catch and this is my request query

this is my app.js

const express = require('express');
const app = express();
const morgan = require('morgan');
const mongoose = require('mongoose');
require('dotenv').config()


mongoose.connect(`mongodb+srv://vadim:${process.env.MONGO_ATLAS_PS}@cluster0-abuqs.mongodb.net/shop`, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const productRoutes = require('./api/routes/

app.use(morgan('dev'));

app.use('/products', productRoutes);

module.exports = app;

and this my router of products.js

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Product = require('../models/product')

router.post("/", (req, res, next) => {
    console.log(JSON.stringify(req.body))
    const product = new Product({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        price: req.body.price
    });
    product
        .save()
        .then(result => {
            console.log(result);
            res.status(201).json({
                message: "Handling POST requests to /products",
                createdProduct: result
            });
        })
        .catch(err => {
            console.log(err);
            res.status(500).json({
                error: err
            });
        });
});

and model of product.js

const mongoose = require('mongoose');

const productSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: String,
    price: Number
});

module.exports = mongoose.model('Product', productSchema);

Solution

  • You need to use body-parser to catch data with POST method with express.

    First, you need to install it:

    npm install body-parser --save
    

    Then in your code:

    const express = require('express');
    const router = express.Router();
    const mongoose = require('mongoose');
    const Product = require('../models/product');
    const bodyParser = require('body-parser');
    
    express.use(bodyParser.json());
    
    express.post("/", (req, res, next) => {
        console.log(JSON.stringify(req.body))
        const product = new Product({
            _id: new mongoose.Types.ObjectId(),
            name: req.body.name,
            price: req.body.price
        });
        //The rest of your code
    });
    

    For more about it, read the package docs.