【发布时间】:2017-02-20 18:04:53
【问题描述】:
我正在尝试使用我的(CORS 兼容)RESTful 服务
@Path("/greeting")
@GET
@Produces("application/json")
public Response greeting() {
String result = "{\"id\":1,\"content\":\"Hello, World!\"}";
return Response.ok() //200
.entity(result)
.header("Access-Control-Allow-Origin", "*")
.build();
}
来自我的 AngularJS 应用程序。
function ($scope, $http) {
$scope.dashboard = "ESCO Dashboard";
console.log('start');
// Simple GET request example:
$http({
method: 'GET',
url: 'http://localhost:8080/NobelGrid/api/users/greeting'
}).then(function successCallback(response) {
console.log('success');
$scope.greeting = response.data;
}, function errorCallback(response) {
console.log('error');
});
console.log('end');
}
但我有这个错误:
XMLHttpRequest 无法加载 http://localhost:8080/NobelGrid/api/users/greeting。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://localhost:63342' 因此不允许访问。
使用 Chrome 的控制台网络,这似乎是真的,因为响应标头是:
无论如何从浏览器而不是从 Angular 应用程序访问 REST 服务,标头是正确的
我也试过这个教程:
https://spring.io/guides/gs/consuming-rest-angularjs/
使用他们的 RESTful 服务(他们说也兼容 CORS),但结果是一样的。
ps:我使用 WebStorm 作为 IDE。
更新 - 已解决
在服务器端编写此处理程序:
@Path("/greeting")
@OPTIONS
@Produces("application/json")
public Response greetingOPT() {
return Response.status(200) //200
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia,Authorization")
.build();
}
它有效。一开始它给了我另一个错误:
预检中的 Access-Control-Allow-Headers 不允许请求标头字段授权 [..]
但是将Authorization 添加到GET 和POST 的Access-Control-Allow-Headers 可以解决问题。
【问题讨论】:
标签: javascript angularjs rest jersey cors