node.js - 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);
});
解决方案
将标头 {"Content-Type":"application/json"} 添加到您的 http.post 请求中。
推荐阅读
- docker - 如何使用 Docker Desktop for Windows Kubernetes 和 ingress-nginx 公开 postgres tcp 端口
- asp.net-core - 具有基本身份验证的 ASP.NET Core OAuth
- mysql - 从两个表中选择所有数据,从第一个表中按项目分组(基本 SQL)
- javascript - 如何将网站链接添加到 HTML 网站?
- android - 如何在 ConstraintLayout 中设置视图的最小百分比宽度
- python - 从 python 运行 bash 脚本时自动回答 Python 运行的批处理脚本的输入提示
- go - 如何使用 golang 绑定到带有 TLS 的 LDAP 服务器?
- sql-server - 如何从 sqlproj 文件中引用部署贡献者?
- redis - Heroku python NLP 搜索后台任务
- java - 如何在 JAVA 中将日期对象作为参数发送