javascript - AngularJs 模板 url 加载抛出 CORS 错误

标签 javascript angularjs cors

我使用 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/

相关文章:

javascript - 使用 Javascript 从远程端点将 html 内容附加到 div 中

javascript - 为什么 JavaScript 会跳过我的函数?

javascript - 单元测试 Angular Directive(指令)被文本区域取代

javascript - 为什么 $http.get 返回 304 错误

ajax - 在 IE7 中需要一个跨域 ajax 帖子的解决方法

javascript - 如何在 Javascript/Jquery 中的不同子域上调用 API

javascript - 如何使用 Access-Control-Allow-Origin : https://www. example.com?

javascript - 当对象不再被引用时clearInterval?

AngularJS - templateUrl 路径附加到 href 路径

javascript - JsPDF .save() 不起作用