CORS 与 XMLHttpRequest 不起作用

use*_*483 7 html javascript xmlhttprequest

我尝试使用 XMLHttpRequest 读取音频流,但收到错误“XMLHttpRequest 无法加载。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 Origin“null””。我尝试使用此示例中的 CORS

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>AUDIO</title>
  </head>
  <body>
    <script type="text/javascript">
        函数createCORSRequest(方法,url){
        var xhr = new XMLHttpRequest();
        if (xhr 中的“withCredentials”) {
          // 适用于 Chrome/Firefox/Opera/Safari 的 XHR。
          xhr.open(方法, url, true);
        } else if (typeof XDomainRequest != "未定义") {
          // IE 的 XDomainRequest。
          xhr = new XDomainRequest();
          xhr.open(方法, url);
        } 别的 {
          // 不支持 CORS。
          xhr = 空;
        }
        返回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>
Run Code Online (Sandbox Code Playgroud)

</body> </html>

。如果我像这样将 url 放入音频 html 标签中
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>AUDIO</title>
  </head>
  <body>
    <audio src='http://streaming.radionomy.com/VWClassicRock' controls></audio>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud),然后就可以了。我应该怎么做,才能将它与 XMLHttpRequest 一起使用?

小智 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))
Run Code Online (Sandbox Code Playgroud)

首先,XMLHttpRequest 对象执行OPTIONS调用,以便了解哪些方法可用于端点 URL。CORS 标头也从服务器返回。通过此信息,XMLHttpRequest 知道它是否可以执行 POST 调用。如果允许 CORS,XMLHttpRequest 就可以工作。

为了测试 XMLHttpRequest 调用,您可以在 postman 或 Rest 客户端工具或 CURL 中执行 OPTIONS 调用:

 curl -X OPTIONS -k -H 'Conte -Type: application/json' -i 'https://yourserver/path/hello' --data '{"message": "hello world"}'
Run Code Online (Sandbox Code Playgroud)

然后你可以执行 POST 调用:

curl -X POST -k -H 'Content-Type: application/json' -i 'https://yourserver/path/hello' --data '{"message": "world"}'
Run Code Online (Sandbox Code Playgroud)

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

    }
}
Run Code Online (Sandbox Code Playgroud)