Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile

Cross Domain RESTful API Calls?

5.00/5 (4 votes)
21 Oct 2014CPOL2 min read 28.5K  
Cross domain RESTful API calls?

Maybe you started moving more of your web app logic to client and relying on RESTful services for client-server communication knowing that someday other people will be able to reuse these services as remote API to your app. When I did, I knew that there was a problem with calling restful services from other site’s JavaScript because of the same origin policy that forbids a browser to make cross domain Ajax calls, but I also knew that all the major web sites allow restful services consuming from JavaScript.

I investigated a bit and here are some alternatives I found for this problem.

JSONP

JSONP is browser hack that became standard solution for cross domain Ajax calls. Browser is hacked by pretending that service is a static JavaScript file. In order for this hack to work, server must support JSONP, which means you might be required to alter your services a bit.

The main issue with JSONP is that it doesn’t support HTTP POST (only HTTP GET). Another potential problem with JSONP is that it is not asynchronous, which means that it would probably block browser which would lead to poor user experience.

CORS

Cross-origin resource sharing (CORS) is a new standard that allows cross-domain Ajax calls. The main issue is that not all main browsers are supported. The biggest problem is partial support in IE8/9 of which next limitations are the biggest problem:

  • Only text/plain is supported for the request's Content-Type header
  • No authentication or cookies will be sent with the request

Server Proxy

Another alternative would be to use server proxy that would execute cross-domain request. In other words, do cross-domain request on server instead in browser because server doesn’t have Same-origin policy limitation. The disadvantage is additional work for your clients that must code server proxy instead of consuming your API right from JavaScript.

cqrs-proxy

iFrame Integration

Although iFrames have cross domain restrictions like Ajax, they are much more flexible, so hidden iFrame can be used to enable cross-domain Ajax. 3rd party web page could load our special iFrame for that could execute Ajax calls on behalf of 3rd party page because it is on the same domain as our API, and then it can send data back to page. For cross origin iFrame communication, Window.postMessage can be used or easyXDM library if older browsers need to be supported.

cqrs-ifrmae

Resources

Image 3

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)