Bodyparser错误。

我没有在Express中使用Bodyparser中间件。 可能是什么问题?

我的代码:

Node.js的:


var express = require('express') , app = express() , expressLayouts = require('express-ejs-layouts'); app.set('view engine', 'ejs'); app.set('layout', 'myLayout'); // defaults to 'layout' app.use(expressLayouts); app.use(app.router); app.use(express.bodyParser()); // <- Problem with this app.get('/', function(req, res){ res.render('aView.ejs', { layout: 'template.ejs' }) // it renders HTML & script }); app.post('/myroute/', function(req, res) { console.log("output if this works"); // this works if(req.body) // this results in false console.log("From client: "+ req.body.param(1, null) ); else // else is run console.log("Client to server AJAX doesn't work"); res.send( JSON.stringify({ test : 'Server to client AJAX work'}) ); // works }); console.log("Node.js server is running"); app.listen(3000); 

客户端代码(jQuery 1.7.1)

 function test() { alert("this 2"); // this works getA(function(dat) { alert("this 4: "+dat.test); // this works }); } function getA(callback) { $.ajax({ url: '/myroute/', type: 'POST', dataType: 'json', data: ['test 1','2', '4', '6'], success: function(data) { if ( callback ) callback(data); }, error: function() { if ( callback ) callback(null); }, complete: function() { alert("Klart"); } }); } 

你有路由器之前的身体分析器(所以当它到达你的处理程序,bodyParser尚未被调用。)将bodyParser之前app.router