I have an AngularJS web application with a RESTful Jersey Api as Backend. I'm making a call to this API
function Create(user) {
return $http.post('http://localhost:8080/NobelGrid/api/users/create/', user).then(handleSuccess, handleError('Error creating user'));
}
This is the code of the API (POST):
/**
* This API create an user
*
* @param data
* @return
*/
@Path("create")
@POST
@Produces("application/json")
public Response create(String data) {
UserDataConnector connector;
JSONObject response = new JSONObject(data);
User userToCreate = new User(response.getString("surname"), response.getString("name"),
response.getString("mail"), response.getString("username"), response.getString("password"), 0);
try {
connector = new UserDataConnector();
connector.createUser(userToCreate);
} catch (IOException e) {
e.printStackTrace();
}
return Response.status(Response.Status.OK) // 200
.entity(userToCreate)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia,Authorization")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT").build();
}
/**
* CORS compatible OPTIONS response
*
* @return
*/
@Path("/create")
@OPTIONS
public Response createOPT() {
System.out.println("Called OPTION for create API");
return Response.status(Response.Status.OK) // 200
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia,Authorization")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS").build();
}
I've added an OPTION API for create
in order to make that API CORS-compatible. In fact the API works well cause the OPTIONS API is called before the POST one and the user is created in my Database. Anyway on front end side I get this error:
XMLHttpRequest cannot load http://localhost:8080/NobelGrid/api/users/create/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 500.
Can anyone please help me?
UPDATE:
stack suggests this question No Access-Control-Allow-Origin header is present on the requested resource as possible duplicate but that solution doesn't work for me cause addHeader(String)
is not present in Response Jersey API.
UPDATE 2
I solved the issue using this solution:
http://www.coderanch.com/t/640189/Web-Services/java/Access-Control-Origin-header-present
But I have another error. I will do another question cause I think it's a different argument.
Thanks in advanced!