简体   繁体   中英

Trouble getting the HTTP response's body on a POST request in Angular

I am making a Registration form on angular 13, but when i receive the response from the API the response I get is always treated as an error and not as the actual response. When everything on the backend is OK, the API sends a 200 HTTP code plus a message in the body's response, and when it doesn't, it sends the code 500 and a error message.

I have tried a lot of different methods to print the response's body on the console but it always prints it as an error.

The code is:

this.http.post\<any\>('http://localhost:8090/register', formData, {observe:'response'})
.subscribe({
next :(response) => console.log('Response',response),
error: (error) => console.log('El error',error.error),
});
.

When looking on the dev tools console after sending a correct form it doesn't show an error with the response and the feedback message can be found on the body, and when I send an incorrect form, the console shows the response as an error (as it is a 500 HTTP code) and the error message is present on the body too.

This is what I' getting: (I tried submitting the same form 2 times, the first comment is what I am getting, (I want to get the red part) and the next 2 comments are for the second submit)

Another thing I wanted to know is if is possible to assign a variable inside the subscribe. I have tried to assign error to a global variable but when I try to print it the dev tools console shows an error saying it doesn't have a type.

Thank you so much!!

Edit: This is what the.network console shows, console headers console response

First let us use a more conventional pattern:

this.http.post<any>('http://localhost:8090/register', formData)
  .pipe(catchError(err => console.error('El error', err))
  .subscribe(data => console.log('Response', data));

This will give you or the error generated by the server or the data the server sent in the console.

Please share the error or data as a comment in this answer and I will update the answer with more help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM