【问题标题】:Post Data into API From flutter将数据从颤振发布到 API
【发布时间】:2020-07-23 14:21:33
【问题描述】:

我有一个 API,它是用 Node.js 编写的。它用于记录目的。现在我正在使用来自颤振应用程序的相同 API 来执行相同的操作。

 API  :  http://192.168.137.1:5050/User/Login

如何从 Flutter 应用向 API 发布数据

Expected Input :
 { Data: { USER_NAME: 'usenmae', PASSWORD: 'password' } }

1.来自 Flutter

static Future<String> loginPost(String email, String password) async {
    Map<String, dynamic> jsonMap = {
      'Data': {'USER_NAME': email,'PASSWORD' : password}
    };
    try {
      final response = await http.post(
         'http://192.168.137.1:5050/User/Login',
        body: jsonMap,
      );
      return response.body;

    } catch (exception) {

    }
    return null;
  }

使用上面的代码 sn-ps 调用 API 后出现一些错误

Error : I/flutter ( 4149): send message exception called
I/flutter ( 4149): type '_InternalLinkedHashMap<String, String>' is not a subtype of type 'String' in type cast

我想通过 api 传递用户名和密码,方法是用另一个 Data 对象包装它们,看起来像 { Data: { USER_NAME: 'usenmae', PASSWORD: 'password' } }

谢谢

【问题讨论】:

    标签: flutter


    【解决方案1】:

    在将数据传递给 http.post() 之前,使用 dart:convert 对 jsonMap 数据进行编码。

    import 'dart:convert' as convert;
    
      final response = await http.post(
        'http://192.168.137.1:5050/User/Login',
        body: convert.jsonEncode(jsonMap),
        headers: {"Content-type" : "application/json"}
      );
    

    【讨论】:

    • 尝试通过使用jsonEncode编码将数据传递给API。但是传递的用户名和密码等数据没有进入API。它在Node js的API端打印req.body时返回null . console.log(req.body); 返回空
    【解决方案2】:

    只需要如前所述编码为 json 并将其放入您的标头 'Content-type': 'application/json'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-14
      • 2021-08-05
      • 2020-12-20
      • 2020-03-15
      • 2022-01-27
      • 2020-04-22
      • 2021-08-05
      • 1970-01-01
      相关资源
      最近更新 更多