Json Flutter - Error with Json post method in Flutter giving HTML error

i am trying to post to an api by flutter but it give me this error :

I/flutter ( 5558): <!DOCTYPE html>
I/flutter ( 5558): <html lang="en">
I/flutter ( 5558): <head>
I/flutter ( 5558): <meta charset="utf-8">
I/flutter ( 5558): <title>Error</title>
I/flutter ( 5558): </head>
I/flutter ( 5558): <body>
I/flutter ( 5558): <pre>Cannot POST /login</pre>
I/flutter ( 5558): </body>
I/flutter ( 5558): </html>
I/flutter ( 5558): POST http://192.168.1.5:5000/login


my code :

void create() async {
Dio dio = Dio();
var response = await http.post('http://192.168.1.5:5000/login',headers: {
"Accept":"application/json",
},body: {
"username": "${usernameController.text}",
"password": "${passwordController.text}"
});
print(response.body);
print(response.request);
}


anyone can help plz ? , this error is very wierd

You wanted to post JSON data using the post request but to the body parameter you are passing Map<String, String> which is a dart object.

So you need to convert this map to a json string. Use the inbuilt dart:convert package to do so

import 'dart:convert'

void create() async {
final Map<String, String> jsonData = {
"username": "${usernameController.text}",
"password": "${passwordController.text}"
};

Dio dio = Dio();
var response = await http.post('http://192.168.1.5:5000/login',headers: {
"Accept":"application/json",
},body: json.encode(jsonData),
);
print(response.body);
print(response.request);
}


Reference: JSON support in dart

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue