【问题标题】:Angular JS : No 'Access-Control-Allow-Origin' header is present on the requested resourceAngular JS:请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】:2023-04-04 10:06:02
【问题描述】:

我正在尝试创建一个网络服务。我在客户端使用 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' 标头。因此不允许访问 Origin 'http://localhost'。”当我尝试使用它时。

【问题讨论】:

    标签: angularjs web-services jakarta-ee cors


    【解决方案1】:

    浏览器将使用 OPTIONS 方法执行预检请求以检查对资源的访问。您需要在 JAX-RS 后端实现一个方法,以响应带有 CORS 标头的 OPTIONS 请求(就像您在“添加”方法中所做的那样)。

    @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();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-01
      • 2015-08-29
      • 2017-02-22
      • 2018-10-31
      • 2019-07-21
      • 2016-08-17
      • 2018-01-03
      • 2018-06-09
      相关资源
      最近更新 更多