1
votes

I'm trying to consume my (CORS compatible) RESTful service

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

from my AngularJS application.

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');

}

but I have this error:

XMLHttpRequest cannot load http://localhost:8080/NobelGrid/api/users/greeting. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.

Using Console Network of Chrome this seems true cause the Response Header is:

enter image description here

Anyway accessing to the REST service from the browser and not from the Angular app, the header is correct

enter image description here

I also tried this tutorial:

https://spring.io/guides/gs/consuming-rest-angularjs/

with their RESTful service (also CORS compatible, they said), but the result is the same.

ps: I'm using WebStorm as IDE.

UPDATE - SOLVED

Writing this handler at server-side:

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

it works. At the beginning it gives to me another error:

Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight [..]

but adding Authorization to the Access-Control-Allow-Headers of the GET and POST resolve the problem.

1

1 Answers

2
votes

Look at the error message:

Response to preflight request

Look at the Network log:

Request Method: OPTIONS

Look at your API:

@GET

You need to write a handler for the preflight OPTIONS request before the browser will make the GET request to the handler you have written.