Issue
I have a login API for a web app in Flutter. Postman and all other apps works fine, but when running through Flutter the XMLHttpRequest error
occurs. Here’s my code:
login() async {
var url = '${Urls.url}auth/signin';
var headers = {
'x-api-key': 'x-api-key',
"Content-Type": "application/x-www-form-urlencoded",
};
// print(headers);
var datas = {
'userId': nameEditingController.text,
'userPwd': passwordEditingController.text
};
// print(datas);
var request = http.Request('POST', Uri.parse(url));
request.bodyFields = datas;
request.headers.addAll(headers);
try {
http.StreamedResponse response = await request.send();
print(response.statusCode);
if (response.statusCode == 200) {
String data = await response.stream.bytesToString();
var jsonR = json.decode(data);
_localStorage['token'] = jsonR['data']['token'];
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => Wrapper()),
(route) => false);
} else {
print(response.reasonPhrase);
}
} catch (e) {
data = 'Server is not accepting your request';
print(e);
}
}
Am I doing something wrong here?
Solution
there is something you should do on your server config you should enable CORS
by adding following to headers (every one you need):
"Access-Control-Allow-Origin": "*"
"Access-Control-Allow-Methods": "GET,POST,PUT"
"Access-Control-Allow-Headers": "X-Requested-With,content-type"
"Access-Control-Allow-Credentials": true
also if you are passing any parameter in header the server side should be expecting it
Answered By – Mahmood Bkh
Answer Checked By – Willingham (FlutterFixes Volunteer)