gpt4 book ai didi

javascript - CORS 与 XMLHttpRequest 不起作用

转载 作者:行者123 更新时间:2023-11-28 08:01:48 26 4
gpt4 key购买 nike

我尝试使用 XMLHttpRequest 读取音频流,但收到错误“XMLHttpRequest 无法加载。请求的资源上不存在“Access-Control-Allow-Origin” header 。因此不允许使用 Origin“null”使用权”。我尝试使用此 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>

。如果我像这样将 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>
,然后就可以了。我应该怎么做才能将它与 XMLHttpRequest 一起使用?

最佳答案

我也遇到了同样的问题。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

关于javascript - CORS 与 XMLHttpRequest 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25296455/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com