UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'body' of undefined

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'body' of undefined

const passport = require('passport')
const User = require('../models/user')

module.exports = async (router) => {
    router
        .route('/auth/register')
        .post( async (req, res) => {
            if (req.body){
                console.log(req.body)
                //prints Object {username: "lkhjk", password: "asdas", role: 0}
                let r = await User.createUser(req.body.username, req.body.password. req.body.role) //throws error on this line
                console.log(r)
                return res.send(r)
            } else return res.status(400).send()
        })
}

你好,如果在 console.log 上它可以毫无问题地打印它,我很难找到为什么它说 req 未定义。 (bodyparser 已配置并且在请求中它具有正确的 headers)

你在这行有错别字:

let r = await User.createUser(req.body.username, req.body.password. req.body.role)

您有 . 而不是 ,。所以 req.body.password.req 未定义。

尝试:

let r = await User.createUser(req.body.username, req.body.password, req.body.role)