CORS 是必须在服务器上修改的设置。它允许外部域请求网页上的资源。简单地更改客户端上的代码不会改变 CORS 的功能。
您可以从“脚本”标签内访问页面的原因是,标签的处理方式与跨源请求的所有其他数据不同。在过去,您可以使用将 JSON 数据存储在 HTML 标签内的 JSONP 将 CORS“破解”到您的系统上。
在 Apache 中启用 CORS:
首先通过键入找到您的 httpd.conf
ps -ef | grep apache
这将为您提供 Apache 的位置。找到该类型后:
<apache-location> -V
这将返回您的 httpd.conf 的确切位置,如下所示:
-D SERVER_CONFIG_FILE="/etc/apache2/apache2.conf"
现在您需要转到 httpd.conf 并输入“/”来搜索<directory>
. 找到标签后,在它之后输入:
Header set Access-Control-Allow-Origin "*"
保存文件并通过运行确认语法正确:
apachectl -t
如果检查无误,请运行优雅重启命令:
apachectl -k graceful
服务器重新启动后,您的文件现在应该可以通过外部脚本访问了。
如果由于错误而无法保存配置,请尝试退出编辑器并键入:
sudo chmod 755 httpd.conf
这使所有者可以完全访问配置文件,但其他人只能读取和执行它(http://en.wikipedia.org/wiki/Chmod)。
要测试这些更改,请在外部服务器上创建一个新的 index.html 文件并使用以下内容加载它:
<!doctype html>
<html>
<head>
<title>TEST</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<!-- Insert Scripts & CSS Here -->
<link rel="stylesheet" type="text/css" href="http://d1e24pw9mnwsl8.cloudfront.net/c/bootstrap/css/bootstrap.min.css">
</head>
<body>
<script>
jQuery.get('yourwebsite.com/file.csv', function(data) {
document.write(data);
});
</script>
</body>
</html>
结果输出应反映 yourwebsite.com/file.csv 上的实时数据源
如果加载该 html 页面显示没有输出,请在 Firefox 上按 f12 打开开发人员的控制台。您很可能会看到一个错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at yourwebsite.com/file.csv. This can be fixed by moving the resource to the same domain or enabling CORS.
这意味着要么 a) 您的 httpd.conf 配置不正确/未保存,要么 b) 您忘记重新启动 Web 服务器。