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

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())引起的;但你可以看到,我把它叫做路线之前。

有线索吗?


当前回答

看来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。

其他回答

添加表达。Urlencoded ({extended: true})到路由可以解决这个问题。

router.post('/save',express.urlencoded({ extended: true }),  "your route");

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

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

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");
});

请求头中的Content-Type非常重要,特别是当你从curl或任何其他工具中发布数据时。

确保你使用的是application/x-www-form-urlencoded, application/json之类的,这取决于你的post数据。将此字段保留为空将使Express混淆。

感谢@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)

如果你使用一些外部工具来发出请求,请确保添加头文件:

内容类型:application / json