Response to preflight request does not pass access control check: In 'Access-Control-Allow-Origin' header is present on the requested resource

0

I'm doing client / server testing where the client is being developed with angularjs and the java + tomcat + jersey server.

When I try to make a client-side post, it gets to the server to the right place, but the answer is that it does not arrive. In the browser console gives the error that is in the title.

The code I have is the following

$http({
  method: 'POST',
  url: 'http://localhost:8080/Arq/xml/AuthorService/login',
  data: login,
  headers: {
    'Content-Type': 'application/json'
  }
}).then(function successCallback(response) {
  console.log('success');
  $scope.app = response.data;
}, function errorCallback(response) {
  $scope.app = response;
});

and on the server

@POST
@Path("/login")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response doLogin() {
  System.out.println("REST API");
  UserModel p1 = new UserModel();
  p1.setEmail("[email protected]");
  p1.setMobile_number(123);
  p1.setName("TESTE");


  return Response.status(200)
    .header("Access-Control-Allow-Origin", '*')
    .header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS")
    .header("Access-Control-Allow-Headers", "Content-Type, Authorization, Content-Length, X-Requested-With")
    .entity(p1)
    .build();
}

The strange part is that if I use POSTMAN everything works fine. If I try through the page I'm developing, it gives error.

Does anyone know how to solve it? I would rather not use a plugin to disable CORS but rather a way through code (it was supposed to be via the Access-Control-Allow-Origin header but it does not work).

    
asked by anonymous 01.06.2017 / 19:59

1 answer

0

I was able to solve the problem by adding this to web.xml

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>
    
02.06.2017 / 10:28