错误"/>
Express 服务器读取 JSON body 错误
您好,我正在尝试将 JSON 文件从 Java 程序发送到运行在 Node.js 上的 Express 服务器。
这是将 JSON 发送到服务器的 Java 方法:
public static void sendToSolver(String file) throws MalformedURLException {
try {
URL url = new URL("http://address/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
try(OutputStream os = con.getOutputStream()) {
byte[] input = file.getBytes("utf-8");
os.write(input, 0, input.length);
}
System.out.println(con.getResponseCode() + " " + con.getResponseMessage());
con.disconnect();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
这是我发送到使用 JACKSon 库生成的服务器的 JSON。将其复制到 JSON 验证器中不会产生任何问题。
[ {
"name" : "Game",
"blocks" : [ {
"shape" : [ 2, 2 ],
"position" : [ 0, 1 ]
}, {
"shape" : [ 2, 1 ],
"position" : [ 0, 0 ]
}, {
"shape" : [ 2, 1 ],
"position" : [ 0, 3 ]
}, {
"shape" : [ 2, 1 ],
"position" : [ 2, 0 ]
}, {
"shape" : [ 2, 1 ],
"position" : [ 2, 3 ]
}, {
"shape" : [ 1, 1 ],
"position" : [ 2, 1 ]
}, {
"shape" : [ 1, 1 ],
"position" : [ 2, 2 ]
}, {
"shape" : [ 1, 1 ],
"position" : [ 3, 1 ]
}, {
"shape" : [ 1, 1 ],
"position" : [ 3, 2 ]
}, {
"shape" : [ 1, 2 ],
"position" : [ 4, 1 ]
} ]
} ]
最后,这是我用来接收此 JSON 的简单快速服务器:
const express = require('express')
const app = express()
app.use(express.json());
const port = 80
app.post('/', (req, res) =\> {
console.log(req.body);
res.send('Data received');
});
所以当我尝试从 Java 程序发送 JSON 时,我收到了 200 响应,但是从 Node.js 打印的请求正文的内容看起来像这样
[
{
name: 'Game',
blocks: [
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object]
]
}
]
所以 name 字段被读取没有问题,但是下面的数组完全被破坏了,它甚至不包含像原始 JSON 那样的十个字段。
我真的不明白这是怎么发生的,因为 JSON 清楚地被发送了,但我看不出这个问题是由 Java 程序引起的,还是由 express/Node 引起的。
回答如下:正如 knittl 所建议的那样,解决方案是使用
JSON.stringify(req.body)
能够以原始形式处理 JSON 的指令。
感谢所有帮助我的人!
更多推荐
Express 服务器读取 JSON body 错误
发布评论