Q:

$http Cross domain access issue exists in header

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?

A:

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. 

