您知道如何使用JavaScript从Apple或Google等网站获取数据吗? “数据”表示文字
我曾尝试检查许多其他论坛,但是当我测试它们的代码时,控制台将打印:
CORS策略已阻止从源“ null”访问“ http://www.apple.com.au/”处的XMLHttpRequest:请求的资源上没有“ Access-Control-Allow-Origin”标头。
makeXMLRequest();
function makeXMLRequest() {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","https://www.apple.com.au",true);
xmlhttp.send();
}
答案 0 :(得分:0)
Cross-Origin Resource Sharing (CORS) 是Web开发中的基础概念。
基本上,大多数公司都不想为不属于它们的客户端应用程序提供内容,主要是出于安全性以及服务器负载方面的考虑。这就是为什么从localhost
使用XHR时,您将无法从google.com
获取内容的原因。
尽管并非所有网页都这样-公共教育API经常配置其CORS标头,以便其内容可在任何地方使用。
演示时间:
// get rejected because of facebook's CORS policy
fetch('https://facebook.com')
.then(console.log)
.catch(console.error);
// works fine
fetch('https://api.github.com')
.then(console.log)
.catch(console.error);