corsangular6ionic4ionic-v1

Ionic v4 withCredentials true giving me cors error


Ionic v1 api call is working with withCredentials true but not ionic v4 code working giving me access control errors

Ionic v1 code

vm.getUser = function (email, password) {
  return $http({
  method: 'POST',
   crossDomain: true,
  dataType: "json",
  url: 'http://localhost:3000/api/login/1',
  contentType: "application/json",
  xhrFields: {
    withCredentials: true
  },
  data: {"email": email, "password": password}
});
 };

**working **

 getUser(){
this.http.post(this.url, 
 {"email": email,      "password": password},
{headers:{Content-Type:'application/json'}, withCredentials:true});

Not working


Solution

  • Https not http

    You should be using https for your url if it supports it, otherwise it's not going to work on modern Android devices.

    They started blocking it a few versions back unless you add extra security settings to allow it.

    CORS error

    This is because Ionic 4 uses a different, more modern, webview. It has many advantages but one issue that it has is that the webview itself enforces CORS.

    The solution though, is not within your app. You need to change the server that the api is running on, it needs to allow the cors policy.

    You should read the official documentation as a starting point but the actual solution will be dependent on how you have written the login api.

    Can you avoid CORS?

    Read the docs here:

    Web Views enforce CORS, so it's important that external services properly handle cross-origin requests. See enable-cors.org and MDN for more details.

    If CORS is not implemented on the server, there is a native plugin that performs HTTP requests in the native layer which bypasses CORS.