1
votes

So in Node/Express, I can see the body value using body-parser and console.log(req) returns JSON with the body value:

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

But req.body always returns undefined. I know the positioning is important, and I've seen a lot of threads on it, but I have my routes in separate files, so I think this is causing some issue.

Here's the app.js code:

//(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))

The form is filled out on account_create route, then the POST is on account_register.

Here is 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

Just in case it is needed, here is the code for the account_create route and 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

1 Answers

2
votes

You can replce account_register file like:

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

Problem is occurred due to misplace of req and res under the function.