接受express.js中的POST请求

时间:2012-07-09 15:37:20

标签: http node.js express

我已经阅读了几个关于如何配置express以侦听POST请求的其他问题,但是当我尝试打印出发送到服务器的简单POST查询时,我不断获得空JSON或未定义。

我有这个设置:

//routes
require('./routes/signup.js')(app);

// Configuration
app.configure(function(){
    app.use(connect.bodyParser());
    app.use(express.methodOverride());
    app.register(".html", hulk);
    app.set('views', __dirname + '/views');
    app.set('view options', {layout: false});
    app.set('view engine', 'hulk');
    app.use(express.static(__dirname + '/public'));
    app.use(app.router);
});

然后routes/signup.js看起来像这样:

var common_functions = require('../common_functions.js');
var views            = require('../views/view_functions.js');
var globals          = require('../globals.js');
var mongoose         = require('mongoose');

//declare classes
var User = mongoose.model('User');

module.exports = function(app){
    /**
     * SignUp GET
     */
    app.get('/signup', function(req, res){
        res.render('signup/signup.html');
    });

   /**
    * SignUp POST
    */
   app.post('/signup', function(req, res){
    console.log(JSON.stringify(req.body));
    console.log(req.body);
    res.send(JSON.stringify(req.body));
});

}

模板如下所示:

{{> header.html }}
{{> navigation.html }}
{{> body.html }}
<form action="/signup" method="post">
    <input name="email"/>
    <input type="submit"/>
</form>
{{> footer.html }}

任何部分人都没有特别感兴趣。

两个console.log的打印输出未定义,而res.send()只返回与之前相同的html。我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

Express首次调用任何路由器的动词函数时,自动安装路由器中间件(如果尚未安装)。因此,通过加载配置块上方的路由,路由器中间件是堆栈中的第一个中间件(在bodyParser之上)。移动配置块下方的路由文件加载将解决此问题。

从Express.js文档的配置部分:

Note the use of app.router, which can (optionally) be used to mount the application routes, otherwise the first call to app.get(), app.post(), etc will mount the routes.

http://expressjs.com/guide.html#configuration