0

A request is sent through Angularjs $http with JSON data to my REST service. When the response is returned, required headers are set as following,

Response.ok()
.entity(emp)
.headers.add("Access-Control-Allow-Origin", "*")
.headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.allow("OPTIONS").build();

But when I send a post request without data,

$http.post('localhost:8000/employer/register')  

it is successful. With data, it fails.

$http({method: 'post', url:serverUrl, data:{name:'abc'}, headers:{'Content-Type':'application/json'} });

This is my Rest service

@Path("/register")
public class EmpService{

@Get
@Path("test")
@Produces
public String test(){
return "works";
}

@Post
@Consumes(MediaType.APPLICATION_JSON)
public Response addEmp(Emp emp){

return Response.ok()
.entity(emp)
.headers.add("Access-Control-Allow-Origin", "*")
.headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.allow("OPTIONS").build();  

Browser console is as following.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8081/employer/register (Reason: CORS header 'Access-Control-Allow-Origin' missing).  
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8081/employer/register (Reason: CORS request failed). 

UPDATE: I found that service is not invoked as no Sys.out.println gives any logs. Anyone know where the problem is?

Wasiq Muhammad
  • 3,080
  • 3
  • 16
  • 29
Débora
  • 5,816
  • 28
  • 99
  • 171

3 Answers3

1

Don't add the headers inside the resource method. Why? The preflight is an OPTIONS request, which is the "pre"-request to get the access control headers. And you don't have an OPTIONS method. The browser will not call the @POST method to get the access control headers. For this reason, you should be using a filter instead, and set the headers there.

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
0

Maybe you should be sending a header not allowed by the server.

Try this:

headers.add("Access-Control-Allow-Headers",
  "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, otherCustomHeader");
Jim Buck
  • 2,383
  • 23
  • 42
  • Thanks Fabio. But I found that, even my service is not invoked with data is passed. Without data, it is success. – Débora May 04 '16 at 18:59
  • You could show the signature of the method on the server? – Fábio Dorea May 04 '16 at 19:11
  • I updated the question with the service class. I added a test rest service method : GET . When I call it, it works. Only problem is the POST method with data. If no data, then it is successful. – Débora May 04 '16 at 19:54
0

Try this.May be your api route of server not allowed headers data that may be caused problem

$http.post(url:serverUrl, data:{name:'abc'}  } );
Wasiq Muhammad
  • 3,080
  • 3
  • 16
  • 29