I am currently developing an AngularJS web application that communicates with a RESTful Jersey Api as its Backend. I have implemented a function to make API calls, and here is an example:
function Create(user) {
return $http.post('http://localhost:8080/NobelGrid/api/users/create/', user).then(handleSuccess, handleError('Error creating user'));
}
Below is the code snippet for the API (POST method):
/**
* This API creates a new 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 have included an OPTIONS API endpoint for create
to ensure CORS compatibility. Despite the functionality working correctly, I am encountering an error on the frontend. The error message reads:
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.
If anyone could provide assistance in resolving this issue, it would be greatly appreciated.
UPDATE:
I came across a similar question on stackoverflow regarding the Access-Control-Allow-Origin header but the suggested solution does not apply to my use case due to the absence of the addHeader(String)
method in Response Jersey API.
UPDATE 2
I managed to resolve the initial issue using a solution found at this link: . However, I am now facing another error, which I believe requires a separate discussion.
Thank you in advance for any assistance!