最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - CORS with XMLHttpRequest not working - Stack Overflow

programmeradmin11浏览0评论

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 = '';

    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='' controls></audio>
  </body>
</html>
, then it works. What should i do, to use it with XMLHttpRequest?

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?

Share Improve this question edited Aug 14, 2014 at 6:58 user2452483 asked Aug 13, 2014 at 21:27 user2452483user2452483 3771 gold badge4 silver badges13 bronze badges 3
  • 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 Commented Aug 13, 2014 at 21:29
  • @elzi, I've tried accessing page both ways – user2452483 Commented Aug 14, 2014 at 6:59
  • Please read the article you linked entirely. You need to do set certain headers like Access-Control-Allow-Origin. – jgillich Commented Aug 14, 2014 at 7:11
Add a comment  | 

2 Answers 2

Reset to default 3

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

how XMLHttpRequest works?

In the CORS specification, the browsers have to perform a preflight request to know which methods are available/allowed: GET, POST, HEAD...

The preflight is performing an OPTIONS request. The OPTIONS itself is a method, so you have to enable/allow it too as the other Http methods.

Here is an example:

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);

    }
}
发布评论

评论列表(0)

  1. 暂无评论