来自正文解析器 Node JS 的不需要的格式

Undesired Format from body-parser Node JS

我有一个 android 应用程序使用以下内容向我发送加速度计数据,其中 body 是一个字符串,如 {"device_name":"device1","time":123123123,"acceleration":1} :

con = (HttpURLConnection) new URL(SERVER).openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);

writer = new OutputStreamWriter(con.getOutputStream());
writer.write(body);
writer.flush();

在服务器端,我使用的正文解析器如下:

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
...
app.post('/' function(req,res {
console.log(req.headers);
console.log(req.body);

当我收到 post 请求时,显示如下:

{ '{"device_name":"device1","time":123,"jerk":21.135843,"acceleration":1}': '' }

我想以 {"device_name":"device1","time":123123123,"acceleration":1} 的形式获取 req.body 是否缺少设置此参数的参数?

谢谢!

更新:

我无法更改客户端代码,因此更改发送的内容类型会更加困难。这是 req.head 日志...

{ 'user-agent': '...(Linux; U; Android 4.1.2;...)',
  host: '...',
  connection: 'Keep-Alive',
  'accept-encoding': 'gzip',
  'content-type': 'application/x-www-form-urlencoded', 
  'content-length': '...' }

您正在上传一个 JSON 字符串,但您没有指示 body-parser 处理这些字符串。

而不是这个:

app.use(bodyParser.urlencoded({extended:false}));

使用这个:

app.use(bodyParser.json());

还要确保您的请求将 Content-Type header 设置为 application/json。如果这不可能,并且您确定上传的内容 总是 将成为 JSON,您可以强制 body 解析器解析 body 作为 JSON 像这样:

app.use(require('body-parser').json({ type : '*/*' }));