【问题标题】:AngularJS: Serving $resource via https, Angular switches from https to httpAngularJS:通过 https 服务 $resource,Angular 从 https 切换到 http
【发布时间】:2014-11-05 22:55:18
【问题描述】:

我在我的 AngularJS 项目中设置了一个 ng-resource,它从 REST API 获取数据。在开发和测试环境中一切正常(都通过 http 运行)。但是,在生产环境中,REST 请求会因 No 'Access-Control-Allow-Origin' header 错误而失败。

整个页面都是通过 https 提供的,因此我希望 Angular 的请求也会离开 https。我使用相对路径(例如 /api/)设置资源,但是 AngularJS 似乎从 https 更改为 http。

我的问题

  1. 即使使用相对 api url,什么可能导致请求为 http 而不是 https?
  2. 是否有任何好的 Angular 文档如何处理 $httpresource 的 https 请求?
  3. 这可能是 nginx 的服务器配置问题吗?在我看来,Angular 似乎只是自动从 https 切换到 http。

完整的错误信息

XMLHttpRequest cannot load http://www.example.com/api/data/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.example.com' is therefore not allowed access.

AngularJS 资源设置

  .factory('Data', ['$resource',
    function($resource){
      return $resource('/api/data\\/', {}, {
          query: {
            url:'/api/data/',
            method: 'GET',
            isArray: true}
      },
      { stripTrailingSlashes: false });
    }])

我已将 AngularJS 项目中的 http 和 https 域列入白名单,但这并没有对 https 请求进行任何更改。

.config(function($sceDelegateProvider) {
  $sceDelegateProvider.resourceUrlWhitelist([
    'self',
    'http://www.example.com/**',
    'https://www.example.com/**'
  ]);
})

【问题讨论】:

  • 我找到了问题的原因:stripTrailingSlashes: false 仅适用于 1.3+ 并且我正在运行 1.2.X 并且我在 url 中有错字。上面的网址是正确的。

标签: javascript angularjs rest nginx https


【解决方案1】:

$sceDelegateProvider 不适用于 https。仅支持 http。

【讨论】:

    【解决方案2】:

    我认为它与 https 无关,您可以将 Https 与 $http 和 $resource 一起使用而无需任何更改。如果只用 https 访问索引,所有请求都是 https。

    问题应该是关于“No 'Access-Control-Allow-Origin' header”。您应该在服务器端启用 CORS。这方面已经有很多指南了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多