TypeError: Cannot destructure property 'userId' of 'req.body' as it is undefined

24,659

Solution 1

app.use(bodyParser.json()) // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }))

I figured out that this code needs to be used before specifying route path.

Solution 2

Here is the solution...yayyy!!

Dont need to install body-parser.

try this:

app.use(express.json())

And specify it before your routes like:

(sequence really matters here!)

app.use(express.json());
app.use('/api', Anyroute)

Solution 3

You might be missing bodyParser:

const bodyParser = require('body-parser')

app.use(bodyParser.json()) // for parsing application/json

Solution 4

In my server.ts I had

app.use('/admin', adminRoutes);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))

which gave error message. Changing to

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))
app.use('/admin', adminRoutes);

made it work. Just as OP said in comment, the order must be body-parser first, then path to routes.

Solution 5

Make sure you pass your data as raw and JSON as shown in the image below.

enter image description here

Share:
24,659
c1t1zenn
Author by

c1t1zenn

Updated on July 09, 2022

Comments

  • c1t1zenn
    c1t1zenn 6 months

    Every Time I try to do a post request in postman to http://localhost:3000/api/orders/new

    I am getting this error: **TypeError: Cannot destructure property 'userId' of 'req.body' as it is undefined. at C:\Users\Web-Developer\Desktop\shoppy\backend\routes\orders.js:70:10 at Layer.handle [as handle_request] (C:\Users\Web-Developer\Desktop\shoppy\backend\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\Web-Developer\Desktop\shoppy\backend\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (C:\Users\Web-Developer\Desktop\shoppy\backend\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\Users\Web-Developer\Desktop\shoppy\backend\node_modules\express\lib\router\layer.js:95:5) at C:\Users\Web-Developer\Desktop\shoppy\backend\node_modules\express\lib\router\index.js:281:22 at Function.process_params (C:\Users\Web-Developer\Desktop\shoppy\backend\node_modules\express\lib\router\index.js:335:12) at next (C:\Users\Web-Developer\Desktop\shoppy\backend\node_modules\express\lib\router\index.js:275:10) at Function.handle (C:\Users\Web-Developer\Desktop\shoppy\backend\node_modules\express\lib\router\index.js:174:3) at router (C:\Users\Web-Developer\Desktop\shoppy\backend\node_modules\express\lib\router\index.js:47:12) **

    const router = express.Router();
    const {database} = require('../config/helpers');
    /* GET ALL ORDERS */
    router.get('/', (req, res) => {
        database.table('orders_details as od')
            .join([
                {
                    table: 'orders as o',
                    on: 'o.id = od.order_id'
                },
                {
                    table: 'products as p',
                    on: 'p.id = od.product_id'
                },
                {
                    table: 'users as u',
                    on: 'u.id = o.user_id'
                }
            ])
            .withFields(['o.id', 'p.title as name', 'p.description', 'p.price', 'u.username'])
            .sort({id: 1})
            .getAll()
            .then(orders => {
                if(orders.length > 0) {
                    res.status(200).json(orders);
                } else {
                    res.json({message: 'Mo Orders Found'})
                }
            }).catch(err => console.log(err));
    })
    /* GET SINGLE ORDER */
    router.get('/:id', (req, res) => {
        const orderId = req.params.id;
        database.table('orders_details as od')
            .join([
                {
                    table: 'orders as o',
                    on: 'o.id = od.order_id'
                },
                {
                    table: 'products as p',
                    on: 'p.id = od.product_id'
                },
                {
                    table: 'users as u',
                    on: 'u.id = o.user_id'
                }
            ])
            .withFields(['o.id', 'p.title as name', 'p.description', 'p.price', 'u.username'])
            .filter({'o.id': orderId})
            .getAll()
            .then(orders => {
                if(orders.length > 0) {
                    res.status(200).json(orders);
                } else {
                    res.json({message: `No Orders Found with orderId ${orderId}`})
                }
            }).catch(err => console.log(err));
    })
    /* PLACE A NEW ORDER */
    router.post('/new', (req, res) => {
        let {userId, products} = req.body;
        console.log(userId, products)
    })
    module.exports = router
    
    • Titus
      Titus over 2 years
      req.body is undefined by default, you need to use a parser middleware, more details
  • c1t1zenn
    c1t1zenn over 2 years
    I don't need to use body parser anymore since express comes bundled with that functionality now.
  • c1t1zenn
    c1t1zenn over 2 years
    The problem was in the sequence of the code in app.js)
  • Andrew Einhorn
    Andrew Einhorn about 2 years
    Aaaaaah, thank you! I was doing the app.use(express.json()) after specifying my routes, and so none of my routes had access to it. Thank you for bolding that ORDER MATTERS!!
  • Ibad Shaikh
    Ibad Shaikh over 1 year
    @AndrewEinhorn glad to help :)
  • Ahmed Shaikh
    Ahmed Shaikh 9 months
    Oh man you are a life saver <3.
  • Rahmat Oktrifianto
    Rahmat Oktrifianto 9 months
    I only use app.use(express.json()) in the main file. It's worked!
  • Rahmat Oktrifianto
    Rahmat Oktrifianto 9 months
    After Express 4.16+, we don't need body-parser again because now included in the default Express package. Thanks. expressjs.com/en/changelog/4x.html