0

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

rtpHarry
  • 13,019
  • 4
  • 43
  • 64
Surya Teja
  • 33
  • 1
  • 6

1 Answers1

1

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.

Community
  • 1
  • 1
rtpHarry
  • 13,019
  • 4
  • 43
  • 64
  • Thanks for the reply, 1. Because of some SSL certifications issue in the Backend we are unable to use https. 2. I am having server already been deployed, so is there any chance that I try to resolve only from client side. – Surya Teja Sep 22 '19 at 15:30
  • I have implemented using native http plugin. How to send cookies to the subsequent requests. Substitute for withCredentials true in native plugin ? I am not able to find. – Surya Teja Sep 22 '19 at 15:43