繁体   English   中英

使用http.post时,Express req.body为空

[英]Express req.body is empty when using the http.post

我不知道为什么req.body是EMPTY ... app.js使用body-parser中间件( http://www.expressjs.com.cn/4x/api.html#req.body

var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// add baseurl
app.use('/api', index);
app.use('/api', users);

user.js的

router.route('/user')
.post(function (req, res, next) {
    console.log(req.body);
    console.log(req.headers);
    //console.log(JSON.parse(Object.keys(req.body)[0]));
    res.json({title: 'RESTful: POST...'});
});

我打印了标题:但是req.body是空的,我使用了JSON.parse(Object.keys(req.body)[0])来解析其他类似问题的结果,但它对我不起作用。 我使用邮递员来请求POST,

{ 'cache-control': 'no-cache',
'postman-token': 'db7766d7-767c-4d33-be3a-acfa18ac1d9c',
'content-type': 'application/x-www-form-urlencoded',
'user-agent': 'PostmanRuntime/6.4.1',
accept: '*/*',
host: 'localhost:3000',
'accept-encoding': 'gzip, deflate',
'content-length': '0',
connection: 'keep-alive' }

邮差截图

您的路线似乎配置正确。 通过尝试使用curl发出相同的请求,我将排除与邮递员有趣的业务。

curl -d "@/path/to/payload.json" -H "Content-Type: application/json" -X POST http://localhost:3000/api/user

那么会发生什么?

编辑:从我在评论中收集的内容来看,您发布的请求看起来像是一个Content-Type: application/x-www-form-urlencoded标头,但是有一个JSON正文{"name":"user"} 换句话说, 内容类型标题和正文不匹配

由于服务器期望URL编码内容,因此无法解析请求正文。 因此,使Content-Type标头与body格式一致非常重要。 所以在这种情况下,你有两个选择。

  1. 保留Content-Type: application/x-www-form-urlencoded并将正文更改为name=user
  2. 相应地将标题更改为Content-Type: application/json并将正文保留为{"name":"user"}

试试这个包。 传递表单数据时非常有用,而不是json格式。

https://www.npmjs.com/package/formidable

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM