首页 > 解决方案 > Http请求发送了一个空的body

问题描述

这是我的帖子请求的代码:

Future<User> createUser(String name,String username,String email,String password, String passwordConfirm, String role) async {
  final response = await http.post('http.register.com',
      body:jsonEncode(<String, String>{
        'name': name,
        'username': username,
        'number': email,
        'password': password,
        'passwordConfirm':passwordConfirm,
        'role':role,
      })
  );
  if (response.statusCode == 200) {
    return User.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to load request');
  }
}

问题是,一旦我发送它,API 的正文就变成空的了。我该如何解决?

_futureUser = createUser(_namecontroller.text ,_usernamecontroller.text,_email.text ,_passwordcontroller.text ,_passwordConfirmcontroller.text, _role);

我放了更多代码,我认为这可能会有所帮助。

标签: flutterdarthttp-post

解决方案


根据post功能文档https://pub.dev/documentation/http/latest/http/post.html
如果bodyStringcontent-type则请求的默认为"text/plain".
如果bodyMapcontent-type则请求的 将默认为"application/x-www-form-urlencoded"
您可以将标题设置为application/json

代码片段

http.post(url,
      headers: {"Content-Type": "application/json"},
      body: body

推荐阅读