首页 > 解决方案 > 来自 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 上完成登录过程,然后重定向到用户个人资料页面。

关于测试或检查什么的任何建议?如果您需要我分享更多代码片段,请告诉我,已经在这里停留了好几个小时......谢谢您的宝贵时间。

标签: node.jsflutterhttpdartdio

解决方案


标题

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

图 1

图 2


推荐阅读