Http request sent an empty body

Viewed 375

This is the code for my post request:

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

The problem is once I sent it, the body goes empty to the API.How could I solve it?

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

I put some more codes,I think it could be helpful.

1 Answers

According to post function document https://pub.dev/documentation/http/latest/http/post.html
If body is String , the content-type of the request will default to "text/plain".
If body is Map , the content-type of the request will default to "application/x-www-form-urlencoded".
You can set header to application/json

code snippet

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