节点-req.body有值,但返回未定义

时间:2019-07-04 06:22:08

标签: javascript node.js express body-parser

因此,在Node / Express中,我可以使用body-parser和console.log(req)返回带有主体值的JSON的主体值:

 body: { email: [Object], cname: '', pass1: '', pass2: '' },

但是req.body总是返回undefined。我知道定位很重要,并且已经看到很多线程,但是我的路由位于单独的文件中,所以我认为这会引起一些问题。

这是app.js代码:

//(1) Server Config
const express = require('express')
const app = express()
const port = 3000
app.set('view engine', 'pug')
const path = require('path')
app.use('/', express.static(path.join(__dirname, '/')))

//(2) Modules
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))

//(3) Routes
app.use(require('./routes/account_create'))
app.use(require('./routes/account_register'))

//(4) Server Start
app.listen(port, () => console.log(`Listening on ${port}`))
mongoose.connect(`mongodb://${db_server}/${db_name}`)
    .then(() => console.log('Connected to DB'))
    .catch(err => console.log(err))

在account_create路由上填写表格,然后在account_register上进行POST。

这是account_register:

const express = require('express')
const router = express.Router()

router.post('/account_register', (res, req) => {
    console.log(req.body) //returns undefined
})

module.exports = router

只要需要,以下是account_create路由和PUG的代码:

const express = require('express')
const router = express.Router()

router.get('/account_create', (req, res) => {
    res.render('account_create')
})

module.exports = router

html
    head
        h1 Create Account
        form(action='/account_register' method='POST')
            .form-group
                label(for='email') E-Mail
                input#email(type='email', name='email')
            .form-group
                label(for='cname') Character Name
                input#cname(type='text', name='cname')
            .form-group
                label(for='pass1') Password
                input#pass1(type='password', name='pass1')
                label(for='pass2') Password Confirmation
                input#pass2(type='password', name='pass2')
            button.btn(type='submit') Register
        script(src='../scripts/account_create.js')

1 个答案:

答案 0 :(得分:2)

您可以像这样替换account_register文件:

const express = require('express')
const router = express.Router()

router.post('/account_register', (req, res) => {
    console.log(req.body) //returns form body data
})

module.exports = router

由于该功能下req和res的位置错误而发生问题。