简体   繁体   English

无法在 Angular 中的 POST 请求中获取 HTTP 响应正文

[英]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.我正在 angular 13 上制作注册表,但是当我收到 API 的回复时,我收到的回复始终被视为错误,而不是实际回复。 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.当后端一切正常时,API 会在正文响应中发送 200 HTTP 代码和一条消息,否则,它会发送代码 500 和一条错误消息。

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.在发送正确的表单后查看开发工具控制台时,它不会显示响应错误,并且可以在主体上找到反馈消息,而当我发送不正确的表单时,控制台将响应显示为错误(因为它是一个 500 HTTP 代码)并且错误消息也出现在正文中。

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)这就是我得到的:(我尝试提交相同的表格 2 次,第一个评论是我得到的,(我想得到红色部分)接下来的 2 个评论是第二次提交)

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编辑:这是 .network 控制台显示的内容,控制台标题控制台响应

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请在此答案中以评论的形式分享错误或数据,我将在更多帮助下更新答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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