解析来自 Node js + 车把的 POST 请求

Posted

技术标签:

【中文标题】解析来自 Node js + 车把的 POST 请求【英文标题】:Parse POST request from Node js + handlebars 【发布时间】:2015-03-08 13:00:30 【问题描述】:

我一直在尝试使用带有把手视图引擎的 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;

【问题讨论】:

【参考方案1】:

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

【讨论】:

以上是关于解析来自 Node js + 车把的 POST 请求的主要内容,如果未能解决你的问题,请参考以下文章

我想将 Head 和 Body 合并到车把中(node.js)

res.render 中的 Express-Node JS 车把模板:如何迭代?

带有预检的 Node.JS 中的跨域 POST 请求?

来自 node.js 服务器的 Ajax POST [重复]

Node.js POST API 和请求正文的解析

Node.js/ Express POST 请求正文被解析为不正确的 JSON