javascript - Get undefined in req.body.id (body-parser and express 4) Nodejs -


app.js:

var express = require('express'); var path = require('path'); var bodyparser = require('body-parser'); var routes = require('./routes/index'); var person = require('./routes/person');  var app = express();  // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug');  app.use(bodyparser.json()); app.use(bodyparser.urlencoded({ extended: false })); app.use(express.static(path.join(__dirname, 'public')));  app.use('/', routes); app.use('/person', person);  module.exports = app; 

routes/person.js:

var express = require('express'); var bodyparser = require('body-parser'); var urlencodedparser = bodyparser.urlencoded({ extended: false }); var router = express.router();  /*  page. */ router.get('/', function (req, res) {     res.render('person', {         message: 'person works'     }); });  router.post('/', urlencodedparser, function (req, res) {     res.send('thank you!');     console.log(req.body.firstname);     console.log(req.body.lastname); }); 

views/person.pug:

    extends layout  block content     h1 welcome #{id}     p= message     br     h2= qstr     br     form(method='post', action='/person')         label first name               input#firstname(type='text')             br            label last name          input#lastname(type='text')         input(type='submit', value='submit') 

questions:

1) necessary in every route add?:

var bodyparser = require('body-parser');  var urlencodedparser = bodyparser.urlencoded({ extended: false }); 

2) why this:

enter image description here

1.you don't need use body-parser in every route. body-parser middleware used obtain data application/x-www-urlencoded content type. if you're sure sure data in body not x-www-urlencoded type, don't need use it.

2.please check if passing data in post request. can use chrome extension postman form kind of query.


Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -