我有这个作为我的快速服务器的配置

app.use(app.router); 
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
//Handles post requests
app.use(express.bodyParser());
//Handles put requests
app.use(express.methodOverride());

但是当我在我的路由中请求req.body.something时,我得到了一些错误,指出body是未定义的。下面是一个使用req的路由示例。身体:

app.post('/admin', function(req, res){
    console.log(req.body.name);
});

我读到这个问题是由缺乏app.use(express.bodyParser())引起的;但你可以看到,我把它叫做路线之前。

有线索吗?


当前回答

正如已经发布在一个评论下,我解决了它使用

app.use(require('connect').bodyParser());

而不是

app.use(express.bodyParser());

我仍然不知道为什么简单的express.bodyParser()不工作…

其他回答

根据@kevin-xue所说,需要声明内容类型。在我的实例中,这只发生在IE9中,因为XDomainRequest不设置内容类型,所以bodyparser和expressjs忽略了请求的主体。

我通过在将请求传递给主体解析器之前显式地设置content-type来解决这个问题,如下所示:

app.use(function(req, res, next) {
    // IE9 doesn't set headers for cross-domain ajax requests
    if(typeof(req.headers['content-type']) === 'undefined'){
        req.headers['content-type'] = "application/json; charset=UTF-8";
    }
    next();
})
.use(bodyParser.json());

看来express不再附带body解析器了。我们可能要单独安装。

var express    = require('express')
var bodyParser = require('body-parser')
var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
app.use(function (req, res, next) {
console.log(req.body) // populated!

更多信息和示例请参阅git页面https://github.com/expressjs/body-parser。

使用这一行在任何get或post请求之前在顶部进行适当的解析:

app.use(express.json()) 

它将json数据解析为Javascript对象。

好吧,这可能听起来很蠢,但对我来说很管用。

作为一个完全的初学者,我没有意识到写作:

router.post("/", (res, req) => {
  console.log(req.body);
  req.send("User Route");
});

是错的!

你必须确保你以正确的顺序传递post/get的参数(req,res):并相应地调用它们:

router.post("/", (req, res) => {
  console.log(req.body);
  res.send("User Route");
});

感谢@spikeyang的精彩回答(如下所示)。在阅读了这篇文章后,我决定分享我的解决方案。

什么时候使用?

解决方案要求你使用快速路由器才能享受它。所以: 如果你试图使用已接受的答案,但运气不好,只需使用复制粘贴这个函数:

function bodyParse(req, ready, fail) 
{
    var length = req.header('Content-Length');

    if (!req.readable) return fail('failed to read request');

    if (!length) return fail('request must include a valid `Content-Length` header');

    if (length > 1000) return fail('this request is too big'); // you can replace 1000 with any other value as desired

    var body = ''; // for large payloads - please use an array buffer (see note below)

    req.on('data', function (data) 
    {
        body += data; 
    });

    req.on('end', function () 
    {
        ready(body);
    });
}

叫它:

bodyParse(req, function success(body)
{

}, function error(message)
{

});

注意: 对于大的有效载荷-请使用数组缓冲区(更多@ MDN)