【问题标题】:nativescript handling REST non-200 responsesnativescript 处理 REST 非 200 响应
【发布时间】:2019-11-13 04:23:12
【问题描述】:

使用 Nativescript-Vue 进行 http 调用,我想优雅地处理 404 和 500。这是我正在使用的代码,它将返回带有 appllication/json 消息的 404:

const httpModule = require("tns-core-modules/http");

httpModule.request({
  url: productApi,
  method: "GET"
}).then((response) => {
  console.log("===> received response: " + JSON.stringify(response));
  let status = response.statusCode;
  console.log("===> received status: " + status);
  if (status === 200) {
    var obj = response.content.toJSON();
    console.log("===>  received [200] json: " +obj);
  }  else if (status === 404) {
    console.log("===>  returned [400] ... returning null " );
  }
}, (e) => {
  console.log("===> AWS Error occurred " + JSON.stringify(e));
});

服务器将返回 404 并带有 application/json 响应 "Product 2420846325 not found" 。我在 Postman 和浏览器中验证了这一点。

但是,我在控制台中看不到任何消息...我看到的最接近的是:

Task <88A2709F-3CAD-4671-9D9F-67A95A177AC4>.<2> sent request, body N 0
Task <88A2709F-3CAD-4671-9D9F-67A95A177AC4>.<2> received response, status 404 content K
Task <88A2709F-3CAD-4671-9D9F-67A95A177AC4>.<2> done using Connection 2
Task <88A2709F-3CAD-4671-9D9F-67A95A177AC4>.<2> response ended
Task <88A2709F-3CAD-4671-9D9F-67A95A177AC4>.<2> summary for task success {transaction_duration_ms=2125, response_status=404, connection=2, protocol="h2", domain_lookup_duration_ms=3, connect_duration_ms=96, secure_connection_duration_ms=74, request_start_ms=106, request_duration_ms=0, response_start_ms=2123, response_duration_ms=2, request_bytes=195, response_bytes=370, cache_hit=1}

我应该如何处理这些非 200 响应,以便我可以向我的用户发送消息?

【问题讨论】:

    标签: javascript nativescript nativescript-vue


    【解决方案1】:

    新手错误,所以也许这可以帮助其他人。

    问题出在这一行:

    console.log("===> received response: " + JSON.stringify(response));
    

    'response' 是一个 httpResponse 对象,所以为了让它工作,我改为:

    console.log("===> received response: " + response.content.toString());
    

    因为这会引发错误,所以从未拾取日志消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-08
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      • 2016-05-03
      • 1970-01-01
      相关资源
      最近更新 更多