JQuery - CORS Request Workaround

Is there no way to perform a cross domain AJAX request without getting a CORS error? Yes, there is a solution. Its called a secondary server. In other words, you can short circuit CORS Requests errors using a secondary server to wrap the response with the required allow-* headers. And this can be accomplished (for free) using openshift.com. In this case I am using openshift to handle a AJAX post request for the itunes RSS feed. The secondary server downloads the XML and adds the CORS headers to the response.

by brady houseknecht

HTML

<script src="https://npmcdn.com/[email protected]/dist/jquery.min.js"></script>
 <script>
    document.write('<a id="githubLink" href="https://github.com/bradyhouse/house/tree/master/fiddles/jquery/fiddle-0038-CorsRequest"' +
      ' target="_blank"><img style="z-index: 1000; position: absolute; top: 0; right: 0; border: 0;" ' +
      'src="https://camo.githubusercontent.com/652c5b9acfaddf3a9c326fa6bde407b87f7be0f4/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6f72616e67655f6666373630302e706e67" ' +
      'alt="Fork me on GitHub"><\/a>');
  </script>
  <textarea class="log" style="width: 100%; height: 200px;">
    loading ...
  </textarea>

JavaScript

(function(app, $, undefined) {
  app.URL = 'https://12-bradyhouse.rhcloud.com/passthru';
  $(document).ready(function() {
    let url = window.location.port ? 'http://' + window.location.hostname + ':' + window.location.port :
      'https://' + window.location.hostname;
    $('.log').height(window.innerHeight);
    $.ajax({
      type: 'POST',
      url: app.URL,
      data: 'url=https://itunes.apple.com/WebObjects/MZStore.woa/wpa/MRSS/featuredalbums/sf=143441/limit=100/genre=20/explicit=true/rss.xml&allowOrigin=' + url + '&allowCredentials=true&allowMethods=GET&allowHeaders=content-type',
      success: function(data) {
        $('.log').text(data);
      },
      dataType: 'html'
    });
  });
})(window.app = window.app || {}, jQuery)