【问题标题】:Receive empty Map when sending over Json to server通过 Json 发送到服务器时收到空地图
【发布时间】:2020-01-17 21:56:49
【问题描述】:

我正在尝试通过 rest api(在 node.js 中创建)与服务器通信。当我创建 post 请求时,它返回 {},并且在服务器端,它也接收到 {},即使我将 json 对象传递给后端。

我做错了什么,我该如何解决?

这是代码

飞镖: 类:

class Post {
  final String id;
  final String title;
  final String description;

  Post({this.id, this.title, this.description});

  factory Post.fronJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      title: json['title'],
      description: json['description'],
    );
  }

  Map<String, dynamic> toJson() => {'title': title, 'description': description};
}

发布请求

 var data = new Post(description: 'my description', title: 'my title').toJson();
  print(data); // {title: my title bro, description: my description}
  final response = await http.post(
    Uri.encodeFull('http://localhost:4000'),
    body: data,
  );
  print(response.body); // Returns {}

服务器(节点)

app.post('/', async (req, res) => {
    console.log(req.body); // Returns {}
    res.send(req.body);
});

【问题讨论】:

    标签: node.js express http flutter server


    【解决方案1】:

    将标头 {"Content-Type":"application/json"} 添加到您的 http.post 请求中。

    【讨论】:

    • 完美!你介意解释一下为什么/如何工作吗?
    • 我不是一个非常有经验的网络程序员,所以请仔细检查一下,据我了解,标题“Content-Type”告诉 API 检查特定的有效负载,无论是字节图像还是一个 JSON。
    猜你喜欢
    • 1970-01-01
    • 2018-02-27
    • 2011-09-25
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 2014-01-03
    • 2018-03-27
    相关资源
    最近更新 更多