1

I am currently writing a feature in the Ionic framework that requires communication with an API. I attempt to use the XMLHttpRequest() function like the majority of resources I found online call for, but the request fails each time, despite the fact that I have internet access, with the cannot load error.

If it makes any difference, I am testing the app with ionic serve --lab, and through a local machine (which is connected to the internet. I guess I am also wondering to some degree what the proper way to communicate with a RESTful API through Ionic would be, as well. Any help would be greatly appreciated.

2
  • could you share the error screenshot? Commented Jun 7, 2016 at 4:08
  • machine can't currently screenshot, but I'll definitely include it in the morning Commented Jun 7, 2016 at 4:20

1 Answer 1

1

The problem is CORS. While you are in your app your mobile phone handles the cross domain connections for you but in your browser its a no go.

What you need to do is setup a proxy using your ionic.project

{
  "name": "appName",
  "app_id": "",
    "proxies": [
    {
      "path": "/devapi",
      "proxyUrl": "https://api.somewebsite.com/api/"
    }
  ]
}

After this every ajax request you do should be simply sent to "/devapi" This is what I did to not switch every 5 seconds between them in my application initlization

if (window.cordova) {
  $rootScope.baseURL = 'https://api.somewebsite.com/api/';
} else {
  $rootScope.baseURL = 'devapi/';
}

Further reading about proxies: http://ionicinaction.com/blog/how-to-fix-cors-issues-revisited/

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

5 Comments

I believe you are absolutely correct in that this is the problem. Think you could elaborate what exactly the /devapi path is? Is it a local directory?
Its like a virtual path. Everytime devapi is in the url its transformed by ionic to the webserver api url. I added a link that explains in depth
Hm. I changed the given information, and on my browser, when I navigate to 'localhost:8100/api/', it redirects me to the proper url with the proper information! However, the network call still fails and returns null..
Did you change the urls you are calling in the ajax calls?
Indeed. I believe the error lies somewhere else at this point, so I'll accept your answer for pointing me in the right direction. Thank you!

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.