0

I have written a simple rest service as a backend, which I call from my frontend Angular webpage. Below is the frontend code that makes the call. Wether or not a valid person is given, the promise gets rejected and the error message is shown.

savePerson(person: Person) {
    const jsonHeader = 'application/json';
    const jsonPerson = JSON.stringify(person);

    return new Promise((resolve, reject) => {
        this.httpClient.post(this.url, jsonPerson, {
            headers: new HttpHeaders()
                .set('Accept', jsonHeader)
                .set('Content-Type', jsonHeader)
        })
            .toPromise()
            .then(
                res => { // Success
                    console.log("success");
                    resolve(res);
                },
                res => {
                    console.log("rejected");
                    reject(res)
                }
            );
    });
}

This code get called after a button is pressed by the user:

 savePerson() {

    this.myService.savePerson(this.person).then(
        result => {
            this.showMessage("Saved");
        },
        error => {
            console.log(error);
            this.showMessage("Error when saving")
        }
    );
}

The logged error (with valid person inputted): Object { headers: {…}, status: 201, statusText: "Created", url: "http://localhost:8080/api/v1.0/person", ok: false, name: "HttpErrorResponse", message: "Http failure during parsing for http://localhost:8080/api/v1.0/person", error: {…} }

I'm assuming this is a problem with the frontend app, since the backend returns a HTTP 201 created. It would be great if anyone could identify the problem for me!

Cœur
  • 37,241
  • 25
  • 195
  • 267
Coen000
  • 79
  • 5
  • 5
    What does `error: {…}` says ? – Royi Namir Nov 26 '17 at 15:35
  • 4
    For what it's worth, that code is falling prey to [the Promise creation anti-pattern](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it#). There's no need for `new Promise` there at all. – T.J. Crowder Nov 26 '17 at 15:42
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Nov 26 '17 at 23:05

1 Answers1

1

Angular is trying to parse the HTTP response and your server is (I guess) answering with a blank HTTP response. Telling Angular the response is just text should fix the error :

this.httpClient.post(this.url, jsonPerson, {
    responseType: 'text',
    headers: new HttpHeaders()
        .set('Accept', jsonHeader)
        .set('Content-Type', jsonHeader)
})
Fathy
  • 4,939
  • 1
  • 23
  • 25