postman TypeError:无法解构'req.body'的属性'userId',因为它未定义

bhmjp9jg  于 2022-11-23  发布在  Postman
关注(0)|答案(7)|浏览(186)

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
nfeuvbwi

nfeuvbwi1#

这就是解决方案......耶!!

不需要安装主体解析器。
试试这个:

app.use(express.json())

并在路由之前指定它,例如:

(顺序在这里非常重要!)

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

iugsix8n2#

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

我发现在指定路由路径之前需要使用此代码。

sycxhyv7

sycxhyv73#

在我的server.ts里我有

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

发出错误消息将更改为

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

就像OP在注解中说的,顺序必须是首先是主体解析器,然后是路径到路由。

at0kjp5o

at0kjp5o4#

您可能缺少bodyParser
const bodyParser = require('body-parser')
app.use(bodyParser.json()) // for parsing application/json

ngynwnxp

ngynwnxp5#

确保以rawJSON的形式传递数据,如下图所示。

nimxete2

nimxete26#

app.use(express.urlencoded({ extended: true }));

express urlencoded()函数是Express中内置的中间件函数,它解析带有urlencoded有效负载的传入请求,并且基于body-parser

amrnrhlw

amrnrhlw7#

添加以下中间件

// middlewares
app.use(express.json)
app.use(cors)

相关问题