【问题标题】:Not getting http error codes from rest calls没有从 rest 调用中获取 http 错误代码
【发布时间】:2018-06-17 04:00:39
【问题描述】:

我需要能够区分应用程序中不同流程的 400 和 500 范围错误代码。

假设我有 3 个休息电话,

  • 首先将返回 200,
  • 秒将返回 401,
  • 第三个将返回 502

我开始使用 aurelia-http-client,这是我第一次注意到我在 promise 的拒绝回调中收到 http 错误 code = 0

更新:使用 aurelia-fetch-client 仅返回一个字符串作为错误响应,因此也不是一个选项。

然后我尝试使用ajax call 和basicXMLHttpRequest,产生了相同的结果。对于 200 范围,我得到了代码,但以上任何内容,我收到的 statusCode 为 0。

更新:我正在运行 63.0.3239.132 版的 Chrome,如果它有所作为的话。

我尝试过的:

  • 我已经尝试了大约 5 种不同的 fetch 变体。

    fetch(url, {
      method: requestMessage.method,
      headers,
      body: JSON.stringify(content)
    })
    .then((result) => {
      resolve(result)
    })
    .catch((error) => {
      reject(error); 
    });
    
  • 输出字符串错误

使用aurelia-http-client

    this.httpClient.createRequest(url)
      .asPut()
      .withContent(params)
      .send()
      .then((response) => {
        resolve(response);
      },
      (error) => {
        reject(error);
      });

- 对于错误,StatusCode 始终为 0

另外(这只是建立了一个动态的 XmlHttpRequest):

private retryRequest(): void {
  var xhr = this.setupXhr();
  xhr.onreadystatechange = () => this.stateChange(xhr);
  setTimeout(() => {
    xhr.send(JSON.stringify(this.content));
  }, 1000);
}

private setupXhr(): XMLHttpRequest {
  var xhr = new XMLHttpRequest();
  xhr.open(this.method, this.url, true);
  xhr = this.addHeaders(xhr);
  return xhr;
}

private addHeaders(xhr: XMLHttpRequest): XMLHttpRequest {
  for (let key in this.headers) {
    if (this.headers.hasOwnProperty(key)) {
      xhr.setRequestHeader(this.headers[key].key, this.headers[key].value);
    }
  }
  return xhr;
}

private stateChange(xhr: XMLHttpRequest): void {
  logger.debug(' ::>> xhr = ', xhr);
  if (xhr.readyState === 4) {
    if (xhr.status >= 200 && xhr.status < 400) {
      this.resolve(JSON.parse(xhr.response));
    } else if (xhr.status >= 500) {
      this.retryRequest();
    } else {
      // this.retryRequest();
      this.reject(xhr.response); // call after a # of fails for this ??? 
    }
  }
}
  • 仅返回 200 范围的 http 状态代码

还有:

    $.ajax({
      type: requestMessage.method,
      url,
      data: JSON.stringify(content),
      headers,
      success: (data) => {
        logger.debug(' ::>> rest call was a success ', data);
        resolve(data);
      },
      statusCode: {
        502: (jqXHR) => {
          logger.debug(' ::>> received 502 ');
          var retryAfter = jqXHR.getResponseHeader('Retry-After');
          retryAfter = parseInt(retryAfter, 10);
          if (!retryAfter) { retryAfter = 5 };
          setTimeout(query, retryAfter * 1000);
        }
      }
    });

- 永远不会得到 502 回调。我也尝试过其他状态码

有没有办法获取我可能遗漏的错误代码?任何帮助表示赞赏

【问题讨论】:

    标签: javascript ajax rest aurelia


    【解决方案1】:

    我有类似的要求,并使用以下代码实现了这一点

    $.ajax({
            type: "POST",
            url: urlAjax,
            dataType: 'json',
            headers: headerValue,
            data: _dataValue,
            crossDomain: true,
            beforeSend: function () {
                //any operation
            },
            complete: function () {
                // any after operation
            },
            success: function (data) {
               // All 2XX will reach here 
            },
            error: function (jqXHR, textStatus, error) {
                var Check = JSON.parse(jqXHR['responseText']);
                // In above array you will get whole error response
            }
        }).done(function (rs, textStatus, xhr) {
            // on finished
        });
    

    jqXHRtextstatuserrror 参数中,您将收到有关错误和相关代码的所有信息。

    希望对您有所帮助。

    【讨论】:

    • 感谢您的快速回复。不幸的是没有运气。看来这个问题可能与我们从服务器收到的响应有关
    【解决方案2】:
    发现问题:

    我最初认为Harshal Bulsara 是解决我的问题的原因。这是一个很好的实现,但我发现了实际问题。

    我发现我们的 nginx 响应没有发送所需的标头。 通过添加 Access-Control-Allow-Origin 标头,我收到了 statusCode。

    【讨论】:

      猜你喜欢
      • 2013-01-29
      • 1970-01-01
      • 2015-04-16
      • 2020-06-10
      • 2019-12-27
      • 1970-01-01
      • 2019-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多