A Grizzly server is running on localhost:8080 that uses Jersey to offer a REST interface.
The CorsFilter class is responsible for creating CORS headers. It is added to the resource config of the GrizzlyServer:
final ResourceConfig rc = new ResourceConfig()
.packages("my.application.api.rest")
.register(new CorsFilter());
GrizzlyHttpServerFactory.createHttpServer(uri, rc); // uri defined earlier
Here is the CorsFilter class as found in another post:
@Provider
public class CorsFilter implements ContainerResponseFilter {
private final String HEADERS = "Origin, Content-Type, Accept";
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException {
response.getHeaders().add("Access-Control-Allow-Origin", "*");
response.getHeaders().add("Access-Control-Allow-Headers", HEADERS);
response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
}
}
There are two classes representing REST handlers: my.application.api.rest.A.class my.application.api.rest.B.class
Both resources A and B have a POST handler:
@Path("/A")
public class A {
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response handlePost()
{
Object payload = getPayload();
return Response.ok(payload).build();
}
}
B looks similar to A.
The client is an AngularJS based web application hosted at a local node server from localhost:3000. The POSTs to /A and /B are done using Restangular:
Restangular.all('A').post({
key: value
});
While POST to A is executed by all available browsers (Chrome, Safari, Firefox), the same POST to B is not executed due to the following error:
XMLHttpRequest cannot load http://localhost:8080/myapplication/B. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500.
I assume that the headers added by CorsFilter are getting lost somewhere.
POSTs with Postman to A and B work well and the header "Access-Control-Allow-Origin: *" is always present.