【问题标题】:Access-Control-Allow-Origin not working in AngularJS applicationAccess-Control-Allow-Origin 在 AngularJS 应用程序中不起作用
【发布时间】: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


    【解决方案1】:

    查看错误信息:

    对预检请求的响应

    查看网络日志:

    请求方法:OPTIONS

    看看你的 API:

    @GET

    您需要为the preflight OPTIONS request 编写一个处理程序,然后浏览器才会向您编写的处理程序发出 GET 请求。

    【讨论】:

    • 嗨@昆汀!我不太明白(对不起):我必须在服务器端为 OPTIONS 编写一个处理程序?或者我必须在客户端做一些事情?非常感谢
    • 您必须在您的服务器上为 OPTIONS 编写一个处理程序(或更改请求,使其不需要预检检查(其细节在答案中链接的另一端进行了描述) ))。
    • 谢谢#Quentin!请问你能看到我的更新吗?
    猜你喜欢
    • 2017-10-20
    • 2017-09-09
    • 2011-09-13
    • 2021-01-01
    • 2017-08-29
    • 2021-09-16
    • 2015-05-02
    • 2013-10-27
    • 2015-09-19
    相关资源
    最近更新 更多