I’m making an app that has a login function. It calls an HTTP POST request to API on my localhost to check the validity of the username and password and if it matches the data on PhpMyAdmin then it will route to the member page.
However, I want to change the await http.post from localhost XAMPP link to a public API link on my hosting. But it throws some errors whenever I do it and when I click on login button nothing happened. Here’s the code:
class _MyHomePageState extends State<MyHomePage> {
TextEditingController user = new TextEditingController();
TextEditingController pass = new TextEditingController();
String msg = '';
Future<List> _login() async {
final response =
await http.post("http://tunnamacbook.local/login.php", body: {
"username": user.text,
"password": pass.text,
});
var datauser = json.decode(response.body);
if (datauser.length == 0) {
setState(() {
msg = "Đăng nhập thất bại";
});
} else {
if (datauser[0]['level'] == 'admin') {
Navigator.pushReplacementNamed(context, '/AdminPage');
} else if (datauser[0]['level'] == 'member') {
Navigator.pushReplacementNamed(context, '/MemberPage');
}
setState(() {
username2 = datauser[0]['name'];
});
}
return datauser;
}
...there's more but it's unnecessary to show here...
Here’s the errors:
[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: FormatException: Unexpected end of input (at character 1)
^
#0 _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1405:5)
#1 _ChunkedJsonParser.close (dart:convert-patch/convert_patch.dart:523:7)
#2 _parseJson (dart:convert-patch/convert_patch.dart:41:10)
#3 JsonDecoder.convert (dart:convert/json.dart:506:36)
2
Answers
I figured it out. It was the problem with the CORS Policy. Setting a CORS allow header in every http API call fixed it. For those who want an example code for this problem, search on Google for CORS allow header for Flutter http call. Since I switched my mobile app programming framework to React Native for better support and a larger Stackoverflow community so I can't write code for this problem in Flutter anymore.
You need to just add ‘Access-Control-Allow-Origin’: ‘*’ in header