Reputation: 713
I am working on a Flutter tablet app. Once one input field is inputted, I am trying to send a post request to the server. Following is the method I am invoking for this:
Future < http.Response > _postRequest() async {
print(globals.novaCoord.toString() + ' XYZXYZXYZXYZXYZ');
var url = globals.URL + 'api/nova_position';
Map data = {
'id_nova': '1',
'position.x': '1',
'position.y': '1',
'position.z': '1',
'position.pitch': '1',
'position.yaw': '1',
'position.roll': '1',
};
//encode Map to JSON
var body = json.encode(data);
http.Response response = await http.post(url,
headers: {
"Content-Type": "application/json"
},
body: body
);
print("${response.statusCode}");
print("${response.body}");
return response;
}
And on the NodeJs server side I have this:
app.post('/api/nova_position/', async (req,res) => {
console.log("NOVA POSITION");
console.log(req.body.id_nova);
const id_nova = req.body.id_nova;
const x = req.body.position.x;
const y = req.body.position.y;
const z = req.body.position.z;
const pitch = req.body.position.pitch;
const yaw = req.body.position.yaw;
const roll = req.body.position.roll;
const position = await db.db.create_position(id_nova,x,y,z,pitch,yaw,roll);
});
However, on the server-side, I am receiving an empty "body" for the request I sent and I receive the following error:
(node:23939) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'x' of undefined
I need help at this point. I appreciate any help and guidance.
Upvotes: 6
Views: 5414
Reputation: 21
The solution I have found was simply to add Content-Length : x
to your header, with x
being the size of your json body.
Upvotes: 2
Reputation: 183
Sending Map<String,dynamic>
with http.post
won't send your data properly.
To solve this, change the content-type of the header to:
Map<String, String> customHeaders = {
...
"content-type": "application/json"
...
};
Then, you can use http.post
as follows:
http.post(url, headers: customHeaders, body);
Upvotes: 12
Reputation: 2021
You have to jsonEncode before pushing into Post request Like
String bodyF = jsonEncode(body);
And i hope you will get your solution.
Upvotes: 4