首页 > 解决方案 > Receive empty Map when sending over Json to server

问题描述

I'm trying to communicate to a server via rest api (which was created in node.js). When I create the post request, it returns {}, and on the server side, it receives {} as well, even though I am passing in a json object to the backend.

What am I doing wrong and how can I fix it?

Here's the code

Dart: Class:

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};
}

Post Request

 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 {}

Server (node)

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

标签: node.jsexpresshttpflutterserver

解决方案


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


推荐阅读