【发布时间】: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。
我的问题
- 即使使用相对 api url,什么可能导致请求为 http 而不是 https?
- 是否有任何好的 Angular 文档如何处理
$http或resource的 https 请求? - 这可能是 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