CORS with XMLHttpRequest not working

I’m trying to read the audio stream using XMLHttpRequest, but get an error “XMLHttpRequest cannot load . No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access”. I tried to use CORS from this example

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>AUDIO</title>
  </head>
  <body>
    <script type="text/javascript">
        function createCORSRequest(method, url) {
        var xhr = new XMLHttpRequest();
        if ("withCredentials" in xhr) {
          // XHR for Chrome/Firefox/Opera/Safari.
          xhr.open(method, url, true);
        } else if (typeof XDomainRequest != "undefined") {
          // XDomainRequest for IE.
          xhr = new XDomainRequest();
          xhr.open(method, url);
        } else {
          // CORS not supported.
          xhr = null;
        }
        return xhr;
      }

  // Helper method to parse the title tag from the response.
  function getTitle(text) {
    return text.match('<title>(.*)?</title>')[1];
  }

  // Make the actual CORS request.
  function makeCorsRequest() {
    // All HTML5 Rocks properties support CORS.
    var url = 'http://streaming.radionomy.com/VWClassicRock';

    var xhr = createCORSRequest('GET', url);
    if (!xhr) {
      alert('CORS not supported');
      return;
    }

    // Response handlers.
    xhr.onload = function() {
      var text = xhr.responseText;
      var title = getTitle(text);
      alert('Response from CORS request to ' + url + ': ' + title);
    };

    xhr.onerror = function() {
      alert('Woops, there was an error making the request.');
    };

    xhr.send();
  }

  makeCorsRequest();
</script>

</body>
</html>. If I put url into audio html tag like this

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>AUDIO</title>
  </head>
  <body>
    <audio src='http://streaming.radionomy.com/VWClassicRock' controls></audio>
  </body>
</html>

, then it works. What should i do, to use it with XMLHttpRequest?

145 thoughts on “CORS with XMLHttpRequest not working”

Leave a Comment