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

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曾经捆绑了许多中间件。bodyParser是附带的中间件之一。当Express 4.0发布时,他们决定从Express中移除捆绑的中间件,并将它们作为单独的包。在安装bodyParser模块后,语法从app.use(express.json())改为app.use(bodyParser.json())。

bodyParser在4.16.0版本中被添加回Express,因为人们希望它像以前一样与Express捆绑在一起。这意味着如果您使用的是最新版本,则不必再使用bodyParser.json()。您可以使用express.json()代替。

对于那些感兴趣的人来说,4.16.0的发布历史在这里,拉请求在这里。

好吧,言归正传,

实现:

你需要加的就是加,

app.use(express.json());
app.use(express.urlencoded({ extended: true}));
app.use(app.router); // Route will be at the end of parser

并删除bodyParser(在新版本的express中不需要)

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

快递公司会处理您的要求。:)

完整的例子是这样的,

const express       = require('express')
const app           = express()

app.use(express.json())
app.use(express.urlencoded({ extended: true}));

app.post('/test-url', (req, res) => {
    console.log(req.body)
    return res.send("went well")
})

app.listen(3000, () => {
    console.log("running on port 3000")
})

其他回答

此问题可能是因为您没有使用body-parser(链接)

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

var app = express();
app.use(bodyParser.json());

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

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

app.use(express.json()) 

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

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

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

首先,确保你已经安装了名为'body-parser'的npm模块,调用:

npm install body-parser --save

然后确保在调用路由之前包含了以下行

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

app.use(bodyParser.json());