我没有让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"); }
});
}
答案 0 :(得分:3)
你在身体解析器之前有路由器(所以当它到达你的处理程序时,bodyParser还没有被调用。)在app.router之前放置bodyParser