Response to preflight request doesn’t pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested Resource

Asked

Viewed 1,112 times

0

I am running client/server tests where the client is being developed with Angularjs and the java server + Tomcat + jersey.

When I try to do a client-side post, it gets to the server at the right place but the answer is that it doesn’t arrive. In the browser console gives the error that is in the title.

The code I have is this:

$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 goes well. If I try through the page I am developing, it is a mistake.

Does anyone know how to fix it? I preferred not to use any plugin to disable CORS but rather a way through code (supposedly it was through the header Access-Control-Allow-Origin but it does not give fully).

1 answer

0


I was able to solve the problem by adding this to the 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.