AngularJS:通过https提供$resource,Angular从https切换到http

AngularJS: Serving $resource via https, Angular switches from https to http

本文关键字:https Angular http resource 通过 提供 AngularJS      更新时间:2023-09-26

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

整个页面都是通过https提供的,因此我希望Angular的请求也会通过https。我用一个相对路径(例如/api/)设置了资源,然而AngularJS似乎从https变成了http。

我的问题

  1. 是什么原因导致请求http而不是https,即使有相对的api url
  2. 关于如何处理$httpresource的https请求,有什么好的Angular文档吗
  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/**'
  ]);
})

我认为它与https无关,您可以使用带有$http和$resource的https而不做任何更改。如果仅使用https访问索引,则所有请求都将是https。

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

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