javascriptjavaangularjsrestjersey

Response.success undefined in angular


I have an AngularJS web application with a RESTful Jersey Api as Backend.

I'm developing and testing this api in order to create user:

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 creates 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(500) // 500
                .entity(e.getMessage()).header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT").build();
        
    }

    return Response.status(200)// 200
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT").build();

}

/**
 * CORS compatible OPTIONS response
 * 
 * @return
 */
@Path("/create")
@OPTIONS
@Produces("application/json")
public Response createOPT() {

    return Response.status(200) // 200
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
            .header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia,Authorization")
            .build();
}

The API works well cause the user is created on back end side (in my own DB)

enter image description here

but on the angular web app the response results to be undefined.

enter image description here

These are my bower's configurations:

 "dependencies": {
"angular": "1.4.x",
"angular-mocks": "1.4.x",
"jquery": "~2.1.1",
"bootstrap": "~3.1.1",
"angular-route": "1.4.x"}

I have also others APIs (GET call) that work well (back end response is 200 and on the web app arrives 200).

Can you help me please?


Solution

  • your backend code has no any body response. add ResponseBuilder entity to your Response.it should be like this:

        return Response.status(Response.Status.OK)// Response.Status.OK: 200
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
                    .entity(userToCreate).build();