'Flutter http.post body is an empty object on nodejs?
My Flutter http.post request is sending an empty body to my Node.js server. Here is my front-end code:
var response = await http.post(Uri.parse('$host/api/new'),
body: {
'id': '$id',
'token': token
});
The post is reaching my node.js server, but the body is an empty object. What am I doing wrong?
Solution 1:[1]
Adding this to the post request fixed it for me:
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
},
Then adding this around the body:
jsonEncode({ ... })
And importing this:
import 'dart:io';
Solution 2:[2]
Try following.
Include headers in request for back end to understand data being sent in json format, and encode data to json.
import 'package:http/http.dart' as http;
import 'dart:convert';
static final client = http.Client();
static Future<dynamic> someFunctionName() async {
//parse URL
var parsedUrl = Uri.parse(URL);
// define headers
Map<String, String> postHeaders = {"Content-Type": "application/json"};
// json encode map
encodedBody = json.encode({'id': '$id','token': token})
// execute http post
var response = await client.post(parsedUrl, headers: postHeaders, body: encodedBody);
print('network_handler.dart - response.body = ${response.body}');
return response;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Page COW |
| Solution 2 | vivek shirodkar |
