我有一个angular.js应用程序,我需要做CORS请求.
我想使用角度资源定义我的休息服务"angular",如下所述:http://docs.angularjs.org/tutorial/step_11.
但我还没有找到办法让这个工作.在谷歌上我发现了以下示例代码:http://jsfiddle.net/ricardohbin/E3YEt/,但这似乎不适用于角度资源.
这是我的app.js
'use strict';
angular.module('corsClientAngularApp', ['helloServices'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
Run Code Online (Sandbox Code Playgroud)
这是我的services.js与其他服务
angular.module('helloServices', ['ngResource']).
factory('Hello', function($resource){
return $resource('http://localhost:8080/cors-server/hello/:name', {}, {
query: {method:'GET', params:{name:'name'}, isArray:false}
});
});
Run Code Online (Sandbox Code Playgroud)
这是我的main.js与控制器使用$ http,这是有效的!:
'use strict';
angular.module('corsClientAngularApp')
.controller('MainCtrl', function ($scope, $http, Hello) {
$http.defaults.useXDomain = true;
$http.get('http://localhost:8080/cors-server/hello/stijn')
.success(function(data) {
$scope.hello = data;
});
});
Run Code Online (Sandbox Code Playgroud)
这是我使用角度资源的main.js的另一个版本.这不起作用:(
'use strict';
angular.module('corsClientAngularApp')
.controller('MainCtrl', function ($scope, $http, Hello) {
$http.defaults.useXDomain …Run Code Online (Sandbox Code Playgroud) 我们在我们的网站上看到了众所周知的CORS错误:
XMLHttpRequest无法加载https://my-site.com/api。所请求的资源上没有“ Access-Control-Allow-Origin”标头。因此,不允许访问来源“ https://my-other-site.com ”。
关键是,在Access-Control-Allow-Origin 被正确设置预检的请求......
OPTIONS https://my-site.com/api HTTP/1.1
Host: my-site.com
Access-Control-Request-Method: POST
Origin: https://my-other-site.com
Access-Control-Request-Headers: my-custom-header, accept, content-type
Accept: */*
Referer: https://my-other-site.com/
...other stuff...
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://my-other-site.com
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: my-custom-header, accept, content-type
Access-Control-Expose-Headers: my-custom-header
...other stuff...
Run Code Online (Sandbox Code Playgroud)
...但是,它没有在后续请求中设置。
POST https://my-site.com/api HTTP/1.1
Host: my-site.com
Accept: */*
My-Custom-Header: abcd123
Origin: https://my-other-site.com
Referer: https://my-other-site.com/
...other stuff...
HTTP/1.1 200 OK
My-Custom-Header: abcd123
...other stuff...
Run Code Online (Sandbox Code Playgroud)
我不明白这个问题。根据我在网上阅读的所有内容,如果我们使用预检请求,则无需为实际请求添加CORS标头。但是,事实显然并非如此。