【问题标题】:CORS with XMLHttpRequest not working带有 XMLHttpRequest 的 CORS 不起作用
【发布时间】:2014-10-07 10:05:28
【问题描述】:

我正在尝试使用 XMLHttpRequest 读取音频流,但收到错误消息“XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' 因此不允许使用权”。我尝试使用来自 example 的 CORS

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>AUDIO</title> </head> <body> <script type="text/javascript"> 函数创建CORSRequest(方法,网址){ var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { // 适用于 Chrome/Firefox/Opera/Safari 的 XHR。 xhr.open(方法,网址,真); } else if (typeof XDomainRequest != "undefined") { // IE 的 XDomainRequest。 xhr = new XDomainRequest(); xhr.open(方法,网址); } 别的 { // 不支持 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>

&lt;/body&gt; &lt;/html&gt;

。如果我像这样将 url 放入音频 html 标记中 &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;AUDIO&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;audio src='http://streaming.radionomy.com/VWClassicRock' controls&gt;&lt;/audio&gt; &lt;/body&gt; &lt;/html&gt;,然后就可以了。我应该怎么做,将它与 XMLHttpRequest 一起使用?

【问题讨论】:

  • 一些示例代码或 URL 会有所帮助。关于 CORS 的文档数不胜数。您正在通过http://localhost/whatever 而不是filesystem://path/to/whatever 访问您的页面,对吗?两个页面是否在同一个域中?
  • @elzi,我尝试过两种方式访问​​页面
  • 请完整阅读您链接的文章。您需要设置某些标题,例如Access-Control-Allow-Origin

标签: javascript html xmlhttprequest


【解决方案1】:

我也遇到了同样的问题。 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', '*');

您可以查看以下要点供您参考:

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

【讨论】:

  • 'Access-Control-Allow-Origin', '*' 是响应头而不是请求头。
  • @kuhajeyan 你是对的。那个时候我还不太了解。
【解决方案2】:

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 调用,以便了解哪些方法可用于 endpointURL。 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"}'

然后您可以执行 POST 调用:

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

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

    }
}

【讨论】:

    猜你喜欢
    • 2013-01-21
    • 2011-05-26
    • 2013-08-20
    • 2012-12-31
    • 2012-09-25
    • 2018-08-21
    • 2013-03-04
    • 2021-07-31
    相关资源
    最近更新 更多