我使用 AngularJS 开发了一个应用。
它位于以下 url,但由于加载模板时出现 CORS 问题而无法正常工作: http://www.ebust.it/app/#/lines/list
该应用程序在没有“www”的网址上运行良好: http://ebust.it/app/#/lines/list
我从 js 控制台得到的错误:
XMLHttpRequest cannot load http://ebust.it/themes/frontend/spa/app/views/lines.html. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.ebust.it' is therefore not allowed access.
我还尝试将模板强制为绝对 URL。你有没有经历过类似的事情?我不明白为什么 Angular 使用错误的域来执行模板 URL 的 AJAX 请求。
最佳答案
当对脚本的请求被重定向时,$http
Ajax 请求变成跨源:
<script src="/themes/frontend/spa/app/scripts/controllers/line.js"></script>
curl -v http://www.ebust.it/themes/frontend/spa/app/scripts/services/line.js
...
< HTTP/1.1 301 Moved Permanently
...
< Location: http://ebust.it/themes/frontend/spa/app/scripts/services/line.js
...
每个脚本都绑定(bind)到为其提供服务的来源,http://ebust.it/
,而不是文档的来源,http://www.ebust.it/
。
要解决这个问题,您可以:
从两个来源提供脚本而不是重定向。
指定为 Ajax URL 中的脚本提供服务的主机名:
return $http({ // ... url: '//ebust.it/line/georeverse' });
用
document.domain
调整原点.document.domain = 'ebust.it';
url: '//' + document.domain + '/line/georeverse'
或者配置 CORS 以允许 2 个源之间的请求。
关于javascript - AngularJs 模板 url 加载抛出 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24616126/