2012-07-09 87 views
0

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

我有这样的设置:

//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 }} 

有nothi特别感兴趣的任何部分。

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

+0

是路由文件之前或配置块后装?如果在此之前,路由器中间件正在被添加到bodyParser之前的堆栈中。将路由文件移动到配置块下面。 – 2012-07-09 15:44:02

+0

是的,完全是它。如果你愿意,可以添加它作为答案,我会接受它!谢谢。总是重要的要记住JavaScript是INTERPRETED NOT COMPILED !!! – 2012-07-09 15:46:38

回答

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