我有这个作为我的快速服务器的配置
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")
})
感谢@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)