postman post raw json 数据, node.js req.body 没有收到
发布于 7 年前 作者 semicoyoung 6709 次浏览 来自 分享

今天项目上有个地方需要post一些json格式的数据,用postman的post方法,body中数据放raw格式, headers中已经设置 content-type : application/json, 但是在服务端,一开始没有app.use(require(‘body-parser’).json()), 因此在req.body中接收不到raw中的json数据,后来app.use(require(‘body-parser’).json()),然后终于看到了。mark一下。

2 回复

http://i5ting.github.io/node-http/#10803

var express = require('./')
var app = express();

app.use(function(req, res, next){
  if (req.is('text/*')) {
    req.text = '';
    req.setEncoding('utf8');
    req.on('data', function(chunk){ req.text += chunk });
    req.on('end', next);
  } else {
    next();
  }
});

app.post('/', function(req, res){
  res.send('got "' + req.text + '"');
});

app.listen(3000)

@i5ting chunk 应该是 Buffer 类型把,Buffer 类型用字串连接可能会出问题。换成 Buffer.concat 方法

回到顶部