解析来自 Node js + handlebars 的 POST 请求

Parse POST request from Node js + handlebars

我一直在尝试使用 Node.js 和 handlebars 视图引擎来解析来自 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;

将路由 and/or 中间件添加到 Express 应用的顺序很重要。因此,在 bodyParser.* 中间件使用后移动 app.use('/', routes);