user2866715
user2866715

Reputation: 21

JAX-RS (jersey) -> Angular.js via REST

I have a jersey server up and running. When running from browser directly I get the correct response. However when I try to access the rest service from angular.js's $resource I get the following error in the console when trying to access to the correct url. I've tried to read all materials online, like http://simplapi.wordpress.com/2013/04/10/jersey-jax-rs-implements-a-cross-domain-filter/ to setup a CORS filter, but the guide seems to be dated and cryptic. (im using the newest implementation of jersey).

Failed to load resource: Origin localhost:63342 is not allowed by Access-Control-Allow-Origin.

method that makes the data I need available in jersey.

  @Path("/id/{id}")
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public boolean validateSSN(@PathParam("id") String id) {
      IdValidator idv = new IdValidator(id);
      return idv.Validate();
  }

accessor method in angular.js:

services.factory('ReplyFactory', function ($resource) {
console.log("test");
return $resource(baseUrl + '/myproject/api/validate/id/:id', {id: '@id'},
    {'get': { method: 'GET' }});

});

Upvotes: 2

Views: 1368

Answers (1)

jusio
jusio

Reputation: 9920

Well what you need to do is to ensure that all responses from your resources have following http headers:

  • Access-Control-Allow-Origin - specifies from which origins requests should be accepted (localhost:63342 in your case)
  • Access-Control-Allow-Headers - specifies which headers are allowed to be used via CORS
  • Access-Control-Allow-Methods - specifies which methods are allowed to be used via CORS

And there are other headers like Access-Control-Allow-Credentials and etc.

So you just need to add at least Access-Control-Allow-Origin header to your responses. How you can do it depends on your environment.

You can manually define those headers on each resource .

You can define Jersey filter to add CORS headers to all responses

You can use servlet filter to add CORS headers to all responses

There are also specific solutions for Tomcat and Jetty

There many ways how to do it but all of it is about the same thing - you just add an extra header to your server responses.

Upvotes: 1

Related Questions