rish rish - 2 months ago 25
reST (reStructuredText) Question

POST method not working in Angular2

I am new in Angular2. I am trying to call simple java REST call from Angular2. When I am posting data I am not getting error at all but my java post method is not called.

Angular2 POST-

let emplyee = JSON.stringify(this.object);
let url = 'http://localhost:8080/rest-app/rest/employeeService/insertEmployee';
console.log("Data: " + emplyee);
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
this.http.post(url, emplyee, options);


Java POST method-

@POST
@Path("/insertEmployee")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String insertEmployee(String employee) {
logger.debug("Employee: " + employee);
return "Hello";
}

Answer

The problem here is that the preflight resuest doesn't pass. You have to allow CORS requests in your Java API (you have to add Access-Control-Allow-Origin * header, see your API lib doc to know how to add it).

That's why you get an error in subscribe, because your preflight request doesn't pass.

EDIT: see How to make CORS-enabled HTTP requests in Angular 2? for more explanations on the problem.

Comments