Last Updated: February 25, 2016
·
7.291K
· marvinroger

Bypassing cross-domain/same-origin policy

Sometimes, when you want to build a simple webapp, you need to issue a request to an external webpage using JS. But you quickly realize you cannot do that because of the same-origin policy.

You basically have 3 warkarounds:

  • Use JSONP, which involves the remote server to be compatible

  • Implement CORS, which also requires the server to support it.

  • Create a proxy supporting JSONP and/or CORS that would request the given external resource server-side, which is not acceptable for a simple webapp running only client side.

Fortunately, there is a free proxy server named CORS Anywhere which adds CORS headers to the proxied request.

There are only two limitations with this approach:

Example (using jQuery)

$.get("http://cors-anywhere.herokuapp.com/http://perdu.com", function(data) {
    alert(data);
});

Note that both the proxy URL and the proxied URL can be https.

Sources: NilsH's answer on StackOverflow