gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:53:32 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com