我没有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之前
关于node.js - Bodyparser错误。,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13306086/