Express 服务器读取 JSON body 错误

编程入门 行业动态 更新时间:2024-10-04 07:26:51

Express 服务器读取 JSON body <a href=https://www.elefans.com/category/jswz/34/1771449.html style=错误"/>

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 错误

本文发布于:2024-05-31 02:19:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771171.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   服务器   Express   body   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!