node.js - 来自 Flutter 中 Dio.Post 方法的 API 中的空响应
问题描述
我一直在尝试使用 Flutter Web 连接到本地 Node JS API。我正在使用带有 GET 和 POST 方法的 Dio dart 包,但是,我的 POST 方法的响应没有返回任何内容。请参阅下面的一些代码实例以及我所看到的:
在我的 Node JS 应用程序中,我收到了来自 Flutter 的信息:
'Server is listening on port 8000'
Successfully connected
/login2
{}
/login2
路径和{}
是console.log
来自 Flutter 传入数据的我的 API 中的一个。现在看 Dio.post 方法:
Future post(String path, Map<String, dynamic> data) async {
try {
final result = await _dio.post(path, data: data);
return result.data;
} catch (e) {
print(e);
throw ('Error en el POST');
}
}
也尝试使用 HTTP,这是一段代码:
Future post2(String id, String password) async {
print(id);
print(password);
final response = await http.post(
Uri.parse('http://localhost:8000/login2'),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode({'user': id, 'password': password}),
);
print(response);
}
我试过邮递员,这就是我得到的:
/login2?user=10002&password=123456
{ user: '10002', password: '123456' }
这就是Flutter 中为空的相同path
查询和查询,这意味着我的 Node 服务器确实在接收数据。{}
console.log
按照@Wali Kan 的建议尝试使用 Postman 配置:
Future post(String path, Map<String, dynamic> data) async {
final String formData = data.toString();
var headers = {'Content-Type': 'text/plain'};
var request =
http.Request('POST', Uri.parse('http://localhost:8000' + path));
request.body = formData;
print(request.body);
http.StreamedResponse response = await request.send();
print(response);
request.headers.addAll(headers);
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
} else {
print(response.reasonPhrase);
}
仍在接收/login2
和{}
在 API 方面。
我缺少的是如何成功接收 Flutter 数据,以便我可以在我的 Node API 上完成登录过程,然后重定向到用户个人资料页面。
关于测试或检查什么的任何建议?如果您需要我分享更多代码片段,请告诉我,已经在这里停留了好几个小时......谢谢您的宝贵时间。
解决方案
标题
HttpHeaders.acceptHeader: "json/application/json",
HttpHeaders.contentTypeHeader: "application/x-www-form-urlencoded"
确保不要FormData.fromMap({})
仅将数据作为普通对象发送,并且不要忘记application/x-www-form-urlencoded
在标题中包含内容类型。如果您的服务器正在运行 express,请确保在处理请求之前拥有这些中间件
app.use(express.json())
app.use(express.urlencoded({ extended: true }));
推荐阅读
- mutiny - Multi / Uni 操作员文档
- firebase - Firebase Auth authStateChanges 触发器
- r - 如何将州名添加到澳大利亚地图?
- r - 在 R 的不同子目录中创建相同的文件夹
- ruby-on-rails - Act_as_Taggable 不返回所选标签上的元素
- google-apps-script - 幻灯片创建上的高级幻灯片 api 未使用预定义布局
- r - R ggmap覆盖geom_contour
- python - 为什么我的烧瓶 sqlalchemy 中的数据没有更新?
- android - Android 11 - 其他人注意到 SetFitsSystemWindows 不起作用?
- python - Python Tkinter Pyscard如何实现PCSC读卡器的实时识别?