1

我没有让 Express 中的 Bodyparser 中间件工作。可能是什么问题?

我的代码:

节点.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"); } 
    });
}
4

1 回答 1

3

你在 body 解析器之前有路由器(所以当它到达你的处理程序时,bodyParser 还没有被调用。)将 bodyParser 放在 app.router 之前

于 2012-11-09T10:37:10.380 回答