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

12

15

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
Galsworthy answered 18/6, 2020 at 17:18 Comment(1)
req.body is undefined by default, you need to use a parser middleware, more detailsUigur
G
19
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.

Galsworthy answered 18/6, 2020 at 18:43 Comment(0)
G
62

Here is the solution...yayyy!!

No 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)
Genoese answered 1/10, 2020 at 12:18 Comment(4)
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!!Twelvetone
@AndrewEinhorn glad to help :)Genoese
Oh man you are a life saver <3.Tommy
I only use app.use(express.json()) in the main file. It's worked!Levelheaded
G
19
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.

Galsworthy answered 18/6, 2020 at 18:43 Comment(0)
H
5

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.

Heelandtoe answered 1/7, 2020 at 10:58 Comment(0)
D
4

You might be missing bodyParser:

const bodyParser = require('body-parser')

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

Diggings answered 18/6, 2020 at 17:28 Comment(2)
I don't need to use body parser anymore since express comes bundled with that functionality now.Galsworthy
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.htmlLevelheaded
B
3

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

enter image description here

Bowing answered 18/6, 2020 at 18:40 Comment(1)
The problem was in the sequence of the code in app.js)Galsworthy
H
3
app.use(express.urlencoded({ extended: true }));

The express urlencoded() function is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser.

Hanukkah answered 11/9, 2022 at 14:21 Comment(0)
E
1

You should app.use(express.json()) before app.use(router). The order of middleware matters.

Eiderdown answered 26/12, 2022 at 21:54 Comment(0)
L
1

Add these line after your models' declaration in index.js

app.use(express.json())
Lablab answered 12/1, 2023 at 3:49 Comment(0)
F
1

app.use(express.json()); add this

Forta answered 22/8, 2023 at 9:19 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Tervalent
F
1

I solve this problem using:

app.use(express.json())

Over routes

Fragment answered 28/12, 2023 at 23:58 Comment(0)
Q
0

Add the following middleware

// middlewares
app.use(express.json)
app.use(cors)
Qulllon answered 28/3, 2022 at 13:17 Comment(1)
Forgot to call json?Embankment
N
0

The order of writing middleware matters, i guess. Previously, this is how my code was:

app.use(authRouter); 
app.use(express.json());

After facing the error i changed it to this:

app.use(express.json());
app.use(authRouter);

then it was working fine.

Niddering answered 3/3 at 9:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.