Angular JS : 请求的资源上不存在 'Access-Control-Allow-Origin' header

Angular JS : No 'Access-Control-Allow-Origin' header is present on the requested resource

我正在尝试创建网络服务。我在客户端使用 AngularJS,在网络服务中使用 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();
    }
}

但是我收到这个错误 - "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access." 当我尝试使用它时。

浏览器将使用 OPTIONS 方法执行预检请求以检查对资源的访问。您需要在 JAX-RS 后端中实现一个方法,以响应 CORS headers 的 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();
}