我正在尝试创建一个网络服务。我在客户端使用 AngularJS,并在 Web 服务中使用 Java。这是我的客户端代码
var url = 'http://localhost:8010/something';
var data = {
"departmentID":$scope.departmentID ,
"departmentName":$scope.departmentName,
};
var config = {
headers: {
'Content-Type': 'Application/JSON',
},
withCredentials : true
};
$http.put(url,data).success(
function(data, status, headers, config){
alert("success :"+data);
}).error(
function(data, status, headers, config){
alert("Failure :"+data);
}
);
这是我的服务器端代码
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response add(final Department department) {
try {
DepartmentRelation.addDepartment(department);
return Response.status(Status.OK).header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT").header("Access-Control-Allow-Credentials",true).build();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
return Response.status(Status.INTERNAL_SERVER_ERROR).header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT").build();
} catch (SQLException e) {
e.printStackTrace();
return Response.status(Status.BAD_REQUEST).header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT").build();
}
}
但我收到此错误 - “请求的资源上不存在“Access-Control-Allow-Origin” header 。因此不允许访问 Origin“http://localhost”。”当我尝试使用它时。
最佳答案
浏览器将使用 OPTIONS 方法执行预检请求来检查对资源的访问。您需要在 JAX-RS 后端实现一个方法,以响应带有 CORS header 的 OPTIONS 请求(就像您在“add”方法中所做的那样)。
@OPTIONS
public Response options() {
return Response
.status(Response.Status.OK)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.header("Access-Control-Allow-Credentials",true)
.build();
}
关于angularjs - Angular JS : No 'Access-Control-Allow-Origin' header is present on the requested resource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28306103/