1

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?

4
  • what about your base url? Does it contain / end of the URL? Commented Sep 7, 2021 at 4:57
  • i think you also forget to encode your data. Commented Sep 7, 2021 at 4:58
  • Check and include CORS headers if not included for the API. Commented Sep 7, 2021 at 5:09
  • refer this answer hope its help to you Commented Sep 7, 2021 at 5:15

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

So this is a server issue? I don't have access to the servers. Devs said they are not receiving any requests to the server. I can sometimes log in when using a VPN.
@JishnuKSanjeevan On the web when you try to do an api call, the browser make a preflight request to check if a certain method is allowed by the server. If the server hasn't that method inside the value of the header Access-Control-Allow-Methods the browser won't make the api call at all. On the server you should see in the logs a request made with the method OPTIONS. That's the preflight request. More info here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.