flutter - no json is sent in the body of my http post

555
Try passing :
Future<http.Response> postRequest () async {
        var url ='http://10.0.2.2:3000/api/message';

       Map<String, String> data = { "message": "opa" };

        var body = json.encode(data);

        var response = await http.post(url,
            headers: { "accept": "application/json", "content-type": "application/json" },
            body: body
        );
        print(response.statusCode);
        print(response.body);
        return response;
      }

      postRequest().then((response){

     print(response.body);
});
Share:
555
johnnnnn
Author by

johnnnnn

Updated on December 13, 2022

Comments

  • johnnnnn
    johnnnnn over 1 year

    this is the code.

          Future<http.Response> postRequest () async {
            var url ='http://10.0.2.2:3000/api/message';
    
            Map data = {
              'message': '12345678901234567890'
            };
            //encode Map to JSON
            var body = json.encode(data);
    
            var response = await http.post(url,
                headers: { "accept": "application/json", "content-type": "application/json" },
                body: body
            );
            print("${response.statusCode}");
            print("${response.body}");
            return response;
          }
    
          postRequest();
    

    // also tried this: headers: {"content-type":"application/json" },

    In my python flask server, the post message is logging, but with empty body into it.

    The flutter app is running on Android Virtual Device and the server is still running on http://0:0:0:0:3000/ and it's using request.get_json() in the method.

    Using postman, everything works as expected on my server so I see the problem in the app.

    postman details:

    POST: http://localhost:3000/api/message

    headers KEY | VALUE Content-Type | application/json

    Body raw

    { "message": "opa" }

    also raised here: https://github.com/flutter/flutter/issues/39351

    • Mohamed Elrashid
      Mohamed Elrashid almost 5 years
      are you using android emulator ?
    • johnnnnn
      johnnnnn almost 5 years
      hi @MohamedElrashid, yes!
  • johnnnnn
    johnnnnn almost 5 years
    Hi Shagun, thanks, but String data = { "message":"opa"}; is not possible. Map<String,String> can't be assgined to a variable of type 'String'.
  • johnnnnn
    johnnnnn almost 5 years
    in my flutter app I added / in the end of url *
  • Shagun Jain
    Shagun Jain almost 5 years
    Yeah, sorry . My mistake, I have edited my code. Please take a look .