【发布时间】: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>
</body>
</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 一起使用?
【问题讨论】:
-
一些示例代码或 URL 会有所帮助。关于 CORS 的文档数不胜数。您正在通过
http://localhost/whatever而不是filesystem://path/to/whatever访问您的页面,对吗?两个页面是否在同一个域中? -
@elzi,我尝试过两种方式访问页面
-
请完整阅读您链接的文章。您需要设置某些标题,例如
Access-Control-Allow-Origin。
标签: javascript html xmlhttprequest