XMLHttpRequest中的CORS不起作用

6
我正在尝试使用XMLHttpRequest读取音频流,但是出现错误“XMLHttpRequest无法加载。请求的资源上没有'Access-Control-Allow-Origin'头。因此不允许访问来自'null'的内容”。我尝试使用这个示例中的CORS:
<!DOCTYPE html></code>
<code><html></code>
  <code><head></code>
    <code><meta charset="utf-8"></code>
    <code><title>AUDIO</title></code>
  <code></head></code>
  <code><body></code>
    <code><script type="text/javascript"></code>
        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;
      }</pre><p></p>

<pre><code>  // 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></code>
<code><html></code>
  <code><head></code>
    <code><meta charset="utf-8"></code>
    <code><title>AUDIO</title></code>
  <code></head></code>
  <code><body></code>
    <code><audio src='http://streaming.radionomy.com/VWClassicRock' controls></audio></code>
  <code></body></code>
<code></html>
, then it works. What should i do, to use it with XMLHttpRequest?


2
一些示例代码或URL将会有所帮助。CORS有无数的文档可供参考。你是通过http://localhost/whatever而不是filesystem://path/to/whatever访问你的页面,对吗?这两个页面是否在同一个域名下? - elzi
@elzi,我已经尝试了两种方式访问页面。 - user2452483
请完整阅读您所链接的文章。您需要设置某些标题,如Access-Control-Allow-Origin - jgillich
2个回答

2
我遇到了同样的问题。CORS错误代表客户端问题,取决于浏览器。当本地服务器向外部服务器发出请求时会发生这种情况。因此,根据您的本地服务器配置,会显示错误。
从我的个人经验来看,我在使用fetch时遇到了这个问题。我在我的php框架上使用了vue.js。所以基本上我发现我必须设置标题,如“X-Requested-With”:“XMLHttpRequest”,“Access-Control-Allow-Origin”:“*”,如果您正在使用fetch方法,则在前端代码请求中使用“mode:'no-cors'”。然后错误就消失了,我可以从前端调用第三方api。
所以您可以执行xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
供您参考,您可以查看这个gist:

https://gist.github.com/khorramk/2c0828ca296832b0319d0155a36af7af以及以下链接: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS


14
“Access-Control-Allow-Origin” 是响应头而不是请求头。 "*" 表示允许来自任何源的跨域请求。 - kuhajeyan
@kuhajeyan 你是正确的。那个时候我还不太了解。 - Khorram Bin Salim Khondkar

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

首先,XMLHttpRequest对象通过进行OPTIONS调用来了解端点URL可用的方法。CORS标头也从服务器返回。有了这些信息,XMLHttpRequest就知道是否可以执行POST调用。 如果允许CORS,XMLHttpRequest将正常工作。
为了测试XMLHttpRequest调用,您可以在Postman或Rest客户端工具中进行OPTIONS调用,或使用CURL:
 curl -X OPTIONS -k -H 'Conte -Type: application/json' -i 'https://yourserver/path/hello' --data '{"message": "hello world"}'

然后您可以执行一个POST调用:
curl -X POST -k -H 'Content-Type: application/json' -i 'https://yourserver/path/hello' --data '{"message": "world"}'

在服务器端不要忘记启用允许的方法:GET、POST、OPTIONS,并返回公开的标头和允许的标头。
@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);

    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接