我从Angular JS代码调用REST服务时遇到了困难:
服务:
app.factory('UserFactory', function ($resource) {
return $resource('http://localhost:8080/demoApp/service/users', {}, {
show: { method: 'GET', isArray: true },
})
});
控制器:
function userListController($scope, UserFactory){
$scope.showUser = function () {
alert("Show user ...");
$scope.fetchedData = [];
$scope.users = UserFactory.show();
$scope.fetchedData.push($scope.users);
};
}
为了克服CORS,我们已经实现了Java CORS Filter,如下所示 -
Following line were written in doFilter method inside a Filter -
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
它与$ http.jsonp完美配合。但是当我们以上述方式调用时,我们在浏览器的Javascript控制台(Chrome)中出现以下错误:
XMLHttpRequest无法加载http://localhost:8080/demoApp/service/users
。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原始http://localhost:63342
访问。
请帮帮我......
此致
Jayanta P。
答案 0 :(得分:1)
非常有帮助。摘录:
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
工作得很好;但是,我必须使用Chrome中提供的CORS插件来禁用Chrome浏览器的安全标记。在那之后,我能够无缝地从我的angularjs应用程序中进行安静的调用。
答案 1 :(得分:0)
你尝试过这样的事吗?
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);