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;
路由/ person.js:
var express = require('express');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var router = express.Router();
/* GET 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);
});
视图/ 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')
问题:
1)是否有必要在每个路线中添加?:
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
2)为什么我这样做:
答案 0 :(得分:0)
1.您不需要在每条路线中使用身体解析器。 Body-parser是一个中间件,用于从application/x-www-urlencoded内容类型中获取数据。因此,如果您确定您的身体数据不是x-www-urlencoded类型,则无需使用它。
2.请检查您是否在邮寄请求中传递数据。您可以使用chrome extension postman来形成任何类型的查询。