节点 - req.body 有值但 returns 未定义

Node - req.body has values but returns undefined

所以在 Node/Express 中,我可以使用 body-parser 和 console.log(req) returns JSON 来查看 body 值:

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

但是req.body总是returns未定义。我知道定位很重要,我已经看到很多关于它的线程,但我的路由在单独的文件中,所以我认为这会导致一些问题。

这是 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 路线上填写,然后 POST 在 account_register 上。

这里是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')

您可以像这样替换 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错位导致问题