Nodejs - Req.body 未定义在 post 中,带有快速 4.9.0
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
来测试它。
快递版本:4.9.0
节点版本:v0.10.33
请帮忙,谢谢。
cURL 对不包含文件的表单提交使用Content-Type: application/x-www-form-urlencoded
。
对于 urlencoding 表单,您的数据需要采用正确的格式:curl -X POST -d 'foo=bar&baz=bla' http://127.0.0.1:3000/module
或 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
的快速配置放在错误的位置。
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;
在定义路由之前,必须确保定义所有快速配置。 因为正文解析器负责解析 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);
});
- 节点.js快速删除 req.body 不起作用
- 在node.jsexpress应用程序中,req.body没有得到<text区域>价值
- 如何从未定义的表单中获取req.body
- post-router的req.body包含新行和冒号
- req.body使用MEAN Express 4.x和Node.js未定义
- 如何在js源节点上将数组作为req.body发送
- Sails.js req.files为空,req.body.image未定义
- 从中间件通过 req.body 传递变量
- express.js req.body 始终为空
- Reactjs req.body shows [object Object]
- req.body 没有给出这个名字
- 无法确定 req.body.name 的值 - 快速节点 JS
- 隐藏/禁用字段从 req.body 中消失(Express JS bodyParser)
- 将 req.body 属性复制到猫鼬模型中时出错
- Express 4 Multer / req.body 和 res.json 未定义
- 节点.JS req.body 字符串太长
- Express API - 验证 req.body 元素
- Nodejs - Req.body 未定义在 post 中,带有快速 4.9.0
- 我无法从nodejs + expressjs中的req.body获取数据
- Express Multer 文件上传 req.body 和 req.file 未定义