我遇到错误并且感到困惑,我使用 Jersey 创建了一个简单的 Java EE 7 项目。
我将在休息服务中返回这门课:
@XmlRootElement
public class LocationDTOx {
private Long id;
private String tittle;
private String description;
private Long parent;
//Getter and setters...
在我的服务级别中,我有:
@Path("/location")
public class LocationService {
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/findlocation")
public LocationDTOx findLocation() {
System.out.println("findlocation");
try {
LocationDTOx x = new LocationDTOx();
x.setDescription("Description");
x.setId(0l);
x.setParent(null);
x.setTittle("Tittle ...");
return x;
} catch (Exception ex) {
Logger.getLogger(LocationService.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
如果我将其放入浏览器中,我 100% 确定我的休息正常:
http://localhost:8080/BIReportL-war/rest/location/findlocation
我得到这个 Json 字符串:
{"description":"描述","id":0,"tittle":"标题..."}
这笔交易在我的 Angular 代码中,我从 Angular 调用其余服务的代码正在执行,但它只是给了我错误部分:
app.controller('questionsController', function ($scope, $http) {
//var url = "http://localhost:8080/BIReportL-war/rest/location/findlocation";
//var url = "http://www.w3schools.com/angular/customers.php";
var url = "http://127.0.0.1:8080/BIReportL-war/json.json";
$http.get(url)
.success(
function (data, status, headers, config) {
alert("success");
})
.error(function(data, status, headers) {
alert('Repos status ' + status + ' --- headers : ' + headers);
})
.finally(
function() {
});
});
我有一个带有注释的另一个本地 URL 到一个虚拟 json 文件,我可以通过该浏览器访问它,而且我也得到了相同的错误结果,奇怪的是我尝试使用这个其余的公共(public) json 文件:
http://www.w3schools.com/angular/customers.php
我成功了!我不知道为什么,我在做什么或者我做错了什么,我的意思是当我尝试使用本地休息服务时,我看到它在日志中被调用,这是事实,但 Angular 客户端正在变得陷入错误。
预先感谢您的帮助!
我正在使用: *玻璃鱼V4 * Angular
嗯,关于 CORS 问题我只是把我的休息如下,所以这里是解决方案:
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/findlocation")
public Response findLocation() {
System.out.println("findlocation");
try {
LocationDTOx x = new LocationDTOx();
x.setDescription("Description");
x.setId(0l);
x.setParent(null);
x.setTittle("Tittle ...");
return Response.ok()
.entity(x)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.build();
} catch (Exception ex) {
Logger.getLogger(LocationService.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
请您参考如下方法:
如果 AngularJS 正在访问您的本地 REST API,那么您在浏览器中的不同端口上运行它这一事实,根据 CORS 的规则(单独的端口),它会被视为不同的来源。表示独立来源)。
Two pages have the same origin if the protocol, port (if one is specified), and host are the same for both pages.
对于您的 Access-Control-Allow-Origin 响应 header ,可以通过 * 将其设置为全部,或者显式指定备用端口。这与您的浏览器(和 AngularJS)试图遵守规则有关,您可以在 MDN's page on same origin policy 上找到这些规则。 .
当您直接在浏览器中加载资源时,这些“规则”不适用,因为来源(浏览器加载的页面)与您加载的端口相同位于该源(加上端口)的资源。
[编辑]
CORS 标准包括遵守某些响应 header ,例如 Access-Control-Allow-Origin 和 Access-Control-Allow-Methods。
引用文献:
[/编辑]