简体   繁体   English

带有 XMLHttpRequest 的 CORS 不起作用

[英]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".我正在尝试使用 XMLHttpRequest 读取音频流,但收到错误“XMLHttpRequest 无法加载。请求的资源上不存在‘Access-Control-Allow-Origin’标头。因此不允许访问 Origin‘null’”。 I tried to use CORS from this example我尝试使用此示例中的CORS

<!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 如果我像这样将 url 放入音频 html 标签中
<!DOCTYPE html>\n<html>\n  <head>\n    <meta charset="utf-8">\n    <title>AUDIO</title>\n  </head>\n  <body>\n    <audio src='http://streaming.radionomy.com/VWClassicRock' controls></audio>\n  </body>\n</html>
, then it works. ,那么它就起作用了。 What should i do, to use it with XMLHttpRequest? 我应该怎么做,将它与 XMLHttpRequest 一起使用?

how XMLHttpRequest works? 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))

First of all the XMLHttpRequest object is doing an OPTIONS call in order to know which methods are available for the endpointURL.首先,XMLHttpRequest 对象正在执行OPTIONS调用,以了解端点 URL 可使用哪些方法。 The CORS headers are returned from the server too. CORS 标头也从服务器返回。 With this information XMLHttpRequest knows if it can perform a POST call.有了这些信息 XMLHttpRequest 就知道它是否可以执行 POST 调用。 If CORS is allowed, XMLHttpRequest is going to work.如果允许 CORS,则 XMLHttpRequest 将起作用。

In order to test the XMLHttpRequest calls, you can do an OPTIONS call in the postman or rest client tool, or a CURL:为了测试 XMLHttpRequest 调用,您可以在 postman 或 rest 客户端工具或 CURL 中执行 OPTIONS 调用:

 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:然后您可以执行 POST 调用:

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

    }
}

I was going through the same problem.我正在经历同样的问题。 The cors errors represent the client side problem depending upon browsers. cors 错误代表客户端问题,具体取决于浏览器。 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.根据我的个人经验,使用 fetch 遇到了这个问题。 I was using vue.js on my php framework.我在我的 php 框架上使用 vue.js。 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.所以基本上我发现我必须设置诸如"X-Requested-With": "XMLHttpRequest", "Access-Control-Allow-Origin": "*"标题,如果您使用的是获取方法使用mode: 'no-cors'在前端代码请求中。 Then the error goes away I can call to third party api from the front end.然后错误消失了,我可以从前端调用第三方 api。

So you can do xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader('Access-Control-Allow-Origin', '*');所以你可以做xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader('Access-Control-Allow-Origin', '*'); 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 https://gist.github.com/khorramk/2c0828ca296832b0319d0155a36af7af和这些链接: https : //developer.mozilla.org/en-US/docs/Web/API/Fetch_API https://developer.mozilla.org/en-美国/docs/Web/HTTP/CORS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM