【问题标题】:How correct handle http post request when server is not available?当服务器不可用时如何正确处理 http post 请求?
【发布时间】:2019-04-03 13:43:03
【问题描述】:

服务器不可用时如何处理正确的http post响应?

现在我发送如下请求:

    this.requestMethods.SendCurrentStep(this.formRegister.currentForm().index).subscribe(() => {
       // TODO
    });

// Code below is not executed father

方法是:

public SendCurrentStep(step: number): Observable<any> {
    return this.http.post('https://localhost:9090/NotAvailableUrl', {
      'step' : step
    })
      .map(res => (<any>res)._body === '' ? {} : res)
      .catch(this.handleError);
  }

【问题讨论】:

    标签: javascript angular angular7


    【解决方案1】:

    当您的服务器不可用时,由RXJS 告诉您。

    this.requestMethods.SendCurrentStep(this.formRegister.currentForm().index)
    .subscribe(
    (sucessResponse) => 
      {
           // TODO your stuff with returned data
      },
    (errorResponse) => 
      {
          // Here if the response is falsey -i.e: code = 500 / 404 ...
      }
    
    );
    

    您无需在应用程序的前端实现任何东西,您只需确保响应代码状态以及响应都从后端很好地发送。 查看here和整个页面)了解更多信息。

    PS:删除 .catch(this.handleError);,我认为和 .map(res =&gt; (&lt;any&gt;res)._body === '' ? {} : res) 一样,因为我不确定那是什么意思。

    【讨论】:

      【解决方案2】:

      您需要从第一个订阅中抛出错误,以便第二个订阅接收它。像这样的...

      public SendCurrentStep(step: number): Observable<any> {
          return this.http.post('https://localhost:9090/NotAvailableUrl', {
            'step' : step
          })
            .map(res => (<any>res)._body === '' ? {} : res)
            .catch((error) =>
          {
             Observable.throw(this.handleError(e)))
          });
        }
      

      然后您可以在第二次订阅中以同样的方式捕获它

      this.requestMethods.SendCurrentStep(this.formRegister.currentForm().index).subscribe(() => {
             // TODO
          }).catch((error) => {
         Console.log("There was a problem sending this request");
      });
      

      这是你的意思吗?如果您的意思是如何判断服务器已关闭,而不是存在内部服务器错误或无效请求 - 您真的不能。你可以使用响应码吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-24
        • 1970-01-01
        • 2020-10-26
        • 2020-06-15
        • 1970-01-01
        • 2016-06-01
        • 2015-08-08
        • 2010-12-08
        相关资源
        最近更新 更多