javascriptjqueryajaxcross-domaincross-domain-policy

How to access the data from different server through AJAX call without JSONP?


I'm working on the project where the client has the back-end code in ServerA, and my front-end code, which is supposed to talk to back-end via AJAX requests is on ServerB, and they are in different domains. Because of the same origin policy, I'm not able to make those requests successfully (neither POST nor GET). Is it possible to enable it somehow without changing the back-end code to handle the JSONP? eg., white list that particular domain, or something?

I tried to emulate this in my local network where the back-end code is running on 10.0.1.4 (different machine), and I'm accessing it from localhost (apache), but couldn't figure out anything that doesn't require using jsonp. When calls are made, I'm not even seeing anything in the logs in the back-end, but it works fine from the REST client and by just loading the URL for GET requests. How are public API requests implemented that are not using JSONP?

I need at least one method (POST or GET) to work. Thanks.


Solution

  • Is it possible to enable it somehow without changing the back-end code to handle the JSONP? eg., white list that particular domain, or something?

    Yes, you could write a server side script on your domain that will serve as a bridge between your and the remote domain and then send an AJAX request to your script.

    Don't expect miracles. If you don't have control over the remote domain you are busted. The same origin policy restriction that's built into browsers for security reasons busts you. Well, you could always write your own browser that doesn't implement this policy, but I think you get my point.

    Common workarounds include JSONP and CORS but they involve control over the remote domain. If you don't have control then read the my previous sentence as well as my first sentence.

    Here's a nice guide I invite you consulting that covers some common techniques allowing to achieve cross domain AJAX with jQuery. Then adapt the one that fits best your scenario. And there's always the heavy artillery solution that involves bridging the 2 domains with a server side script which works bullet-proof in 100% of the cases if none of the other workarounds help you.