2
votes

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?
2
Some example code, or URLs, would help. There's endless documentation on CORS. You're accessing your page via http://localhost/whatever and not filesystem://path/to/whatever, right? Are both pages on the same domain?elzi
@elzi, I've tried accessing page both waysuser2452483
Please read the article you linked entirely. You need to do set certain headers like Access-Control-Allow-Origin.jgillich

2 Answers

1
votes

how XMLHttpRequest works?

const data = '{"message":"hi there!"}'
const xhr = new XMLHttpRequest()
xhr.open('POST', endpointURL)
xhr.setRequestHeader('Content-type', 'application/json')
xhr.send(JSON.stringify(data))

First of all the XMLHttpRequest object is doing an OPTIONS call in order to know which methods are available for the endpointURL. The CORS headers are returned from the server too. With this information XMLHttpRequest knows if it can perform a POST call. If CORS is allowed, XMLHttpRequest is going to work.

In order to test the XMLHttpRequest calls, you can do an OPTIONS call in the postman or rest client tool, or a CURL:

 curl -X OPTIONS -k -H 'Conte -Type: application/json' -i 'https://yourserver/path/hello' --data '{"message": "hello world"}'

and then you can perform an POST call:

curl -X POST -k -H 'Content-Type: application/json' -i 'https://yourserver/path/hello' --data '{"message": "world"}'

In the server side don't forget to enable the allowed methods: GET, POST, OPTIONS, and return the exposedHeaders and allowedHeaders

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST","GET","OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(false).maxAge(3600);

    }
}
1
votes

I was going through the same problem. The cors errors represent the client side problem depending upon browsers. It happens when your local server is making request to external server. Therefore depending upon you local server configuration, the error shows.

From my personal experience came across this using fetch. I was using vue.js on my php framework. So basically what I found is I had to set headers such as "X-Requested-With": "XMLHttpRequest", "Access-Control-Allow-Origin": "*" and if you are using fetch method use mode: 'no-cors' on the front end code request. Then the error goes away I can call to third party api from the front end.

So you can do xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader('Access-Control-Allow-Origin', '*');

For your reference you can look at this gist:

https://gist.github.com/khorramk/2c0828ca296832b0319d0155a36af7af and these link: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS