Nodejs – Req.body未定义在后快速4.9.0

我是nodejs的初学者,我尝试使用中间件体parsing或使用任何东西来知道req.body,但都发现req.body是未定义的。 这是我的代码

var app = require('express')(); var bodyParser = require('body-parser'); var multer = require('multer'); app.get('/', function(req, res) { res.send("Hello world!\n"); }); app.post('/module', function(req, res) { console.log(req); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(multer); console.log(req.body); }); app.listen(3000); module.exports = app; 

我使用命令curl -X POST -d 'test case' http://127.0.0.1:3000/module来testing它。

快递版本:4.9.0
节点版本:v0.10.33

请帮忙,谢谢。

默认情况下,cURL使用Content-Type: application/x-www-form-urlencoded来提交不包含文件的表单提交。

对于urlencoded表单,您的数据需要采用正确的格式: curl -X POST -d 'foo=bar&baz=bla' http://127.0.0.1:3000/modulecurl -X POST -d 'foo=bar' -d 'baz=bla' http://127.0.0.1:3000/module

对于JSON,你必须明确地设置正确的Content-Typecurl -H "Content-Type: application/json" -d '{"foo":"bar","baz":"bla"}' http://127.0.0.1:3000/module

同样,@Brett指出,你需要某个地方(路由处理器之外)的POST路由之前 app.use()你的中间件。

您正在将body-parser的快速configuration放在错误的位置。

 var app = require('express')(); var bodyParser = require('body-parser'); var multer = require('multer'); // these statements config express to use these modules, and only need to be run once app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(multer); // set up your routes app.get('/', function(req, res) { res.send("Hello world!\n"); }); app.post('/module', function(req, res) { console.log(req); console.log(req.body); }); app.listen(3000); module.exports = app; 

在定义路线之前,您必须确保您定义了所有快速configuration。 因为body-parser负责parsing请求的主体。

 var express = require('express'), app = express(), port = parseInt(process.env.PORT, 10) || 8080; //you can remove the app.configure at all in case of it is not supported //directly call the inner code app.configure(function(){ app.use(bodyParser.urlencoded()); //in case you are sending json objects app.use(bodyParser.json()); app.use(app.router); }); app.listen(port); app.post("/module", function(req, res) { res.send(req.body); });