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);
});
Author by
johnnnnn
Updated on December 13, 2022Comments
-
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 almost 5 yearsare you using android emulator ?
-
johnnnnn almost 5 yearshi @MohamedElrashid, yes!
-
-
johnnnnn almost 5 yearsHi Shagun, thanks, but String data = { "message":"opa"}; is not possible. Map<String,String> can't be assgined to a variable of type 'String'.
-
johnnnnn almost 5 yearsin my flutter app I added / in the end of url *
-
Shagun Jain almost 5 yearsYeah, sorry . My mistake, I have edited my code. Please take a look .