[英]Nodejs - Req.body undefined in post with express 4.9.0
我是nodejs的初学者,我尝试使用中间件body-parse或者什么都不知道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
来测试它。
express的版本:4.9.0
节点的版本:v0.10.33
请帮忙,谢谢。
您将body-parser
的express配置放在错误的位置。
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;
默认情况下,cURL使用Content-Type: application/x-www-form-urlencoded
来表示不包含文件的表单提交。
对于urlencoded表单,您的数据需要采用正确的格式: curl -X POST -d 'foo=bar&baz=bla' http://127.0.0.1:3000/module
or curl -X POST -d 'foo=bar' -d 'baz=bla' http://127.0.0.1:3000/module
。
对于JSON,您必须明确设置正确的Content-Type
: curl -H "Content-Type: application/json" -d '{"foo":"bar","baz":"bla"}' http://127.0.0.1:3000/module
。
同样正如@Brett所说,你需要在某个地方(路由处理程序之外)的POST路径之前 app.use()
你的中间件。
您必须确保在定义路由之前定义所有快速配置。 因为body-parser负责解析requst的主体。
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.