我一直在尝试使用带有把手视图引擎的Node.js来解析POST请求中的参数。不知怎的,请求无法解析参数,我认为问题来自于配置app.js.但我无法弄清楚如何解决它。
这是HTML表单
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="/add/complete" method="POST">
<input type="text" name="name" placeholder="Add your kitten name here" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
路由器
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
router.get('/add', function(req, res) {
res.render('add', {});
});
router.get('/meow_response', function(req, res) {
res.render('meow_response', {});
});
router.post('/add/complete', function(req, res) {
// var Kitten = req.Kitten;
console.log(req.body); // PROBLEM: it returns empty, while I expect req.body
res.redirect('/meow_response');
});
module.exports = router;
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var hbs = require('hbs');
var app = express();
hbs.localsAsTemplateData(app);
app.locals.foo = "bar";
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.engine('html', require('hbs').__express);
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
// yay!
});
var routes = require('./routes/routes');
app.use('/', routes);
var kittySchema = mongoose.Schema({
name: String
});
kittySchema.methods.speak = function() {
var greeting = this.name ? "Meow name is" + this.name : "I don't have a name";
console.log(greeting);
}
var Kitten = mongoose.model('Kitten', kittySchema);
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res, next) {
req.Kitten = Kitten;
next();
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
答案 0 :(得分:1)
将路线和/或中间件添加到Express应用程序的顺序很重要。因此,在app.use('/', routes);
中间件使用后移动bodyParser.*
。