CNode

postman post raw json 数据, node.js req.body 没有收到

分享
Ssemicoyoung发布于10 年前最后回复10 年前2 回复7504 浏览0 收藏

今天项目上有个地方需要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)

I
i5ting#1·10 年前

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)
S
stonephp#2·10 年前
引用 i5tinghttp://i5ting.github.io/node http/ 10803

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

参与回复
登录后即可参与回复。登录