【问题标题】:HttpClient.post is successful but Rest API is not getting the dataHttpClient.post 成功但 Rest API 未获取数据
【发布时间】:2021-09-29 06:52:12
【问题描述】:

我正在尝试将我的 Angular 应用程序中的数据存储到数据库中。 我正在使用HttpClient 将数据发布到 RestAPI。它正在发送请求,但 API 未获取数据并返回 response code:500

我尝试将数据记录到控制台,我可以看到数据,但由于某种原因,RestAPI 没有得到它。

我已经尝试用邮递员发送帖子请求并且它有效,所以我怀疑后端是否有任何问题。

【问题讨论】:

    标签: angular typescript http-post rest


    【解决方案1】:

    发布功能后需要订阅。

    this.http.post(`${this.Baseurl}/insertPost`, newPost, this.httpheader).subscribe(
          res => {
             // do something
          },
          err => {
            // do something
          }
    );
    

    【讨论】:

    • 我在另一个组件中调用createPost() this.createpost.createPost(newPost).subscribe( (response:any)=>{ console.log(response); }, (error:any)=>{ console.log(error); }) 这里是函数调用
    【解决方案2】:
    • 如果您没有记录任何内容,那是因为您需要致电 .subscribe().toPromise()
    • 如果您设法记录某些内容,但响应为 null 并返回状态代码 500,则 API 崩溃(出现运行时错误)并且您的请求可能已被取消

    【讨论】:

    • 我已致电.subsribe( ) 并记录了响应和错误。不,API 没有崩溃。我已经尝试使用邮递员发布请求,它工作得很好,但我没有从 Angular 应用程序发出相同的请求
    • 您能分享发送到服务器的请求吗?如果您打开浏览器的开发者工具并检查“网络”>“请求”选项卡,您可以检查一下
    • 还要确保您的对象与您的后端 API 具有相同的形状
    • 这些是Screenhots from Request Tab 抱歉,我不知道还能如何分享。是的,我检查了请求有效负载,它的形状正确。
    • 您能分享一下“响应”标签上的内容吗?屏幕截图仅显示“标题”。在任何情况下,我都可以看到 500,因此请求被触发,但您的服务器正在崩溃,因此对数据库没有副作用
    【解决方案3】:

    正如@YuTing 所说,您需要在调用 post 方法后订阅。

    this.http.post(`${this.Baseurl}/insertPost`, newPost, this.httpheader)
    .subscribe((response: any) =>{
    
    //Here response is the JSON response sent by the server when the API call made.
          if(response){
    
             //do something
    
          }
    });
    

    【讨论】:

      猜你喜欢
      • 2023-01-11
      • 1970-01-01
      • 2015-05-18
      • 2016-05-13
      • 2021-11-09
      • 1970-01-01
      • 2021-05-19
      • 2023-02-14
      • 1970-01-01
      相关资源
      最近更新 更多