node.js - 来自 body-parser Node JS 的不需要的格式

标签 node.js post express body-parser

我有一个 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);

当我收到发布请求时,会显示以下内容:

{ '{"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,则可以强制正文解析器将正文解析为 JSON,如下所示:

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

关于node.js - 来自 body-parser Node JS 的不需要的格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31142328/

相关文章:

node.js - Electron 需要神秘

javascript - React Native - 获取 POST 不起作用

node.js - Node Express 未发送自定义错误消息

node.js - 如何在 express.static() 中获取/发布文件

javascript - Node JS - 根据用户类型显示用户列表

node.js - Nginx 使用 ng-flow 和 Express (Node.js) 挂起请求

python - 从 node.js 和 websockets 访问 IPython 命令行

node.js - 快报- Jade 找不到意见

node.js - 在嵌套表中使用 dataloader-sequelize 显示特定列

http - 使用 Grails 的简单 GET