首页 > 解决方案 > 如何捕获来自 API {} 的空回复

问题描述

我目前正在使用 Node.js 获取 API 数据并将其转换为我自己的 Express.js API 服务器以发送我自己的数据(我使用的 2 个 API 有时会更改结构,并且我有一些用户需要保留相同的结构)。

所以这是我正在使用的代码

app.get('/app/account/:accountid', function (req, res) {
    return fetch('https://server1.com/api/account/' + req.params.accountid)
      .then(function (res) {
      
      var contentType = res.headers.get("content-type");
      if (contentType && contentType.includes("application/json")) {
          apiServer = 'server1';
          return res.json();
      } else {
        apiServer = 'server2';
        throw "server1 did not reply properly";
      }
    }).then(server1Reconstruct).then(function (json) {
      res.setHeader('Content-Type', 'application/json');
      return res.send(json);
    }).catch(function (err) {
      console.log(err);
    }).then(function () {
      if (apiServer == 'server2') {
        server2.fetchAccount({
          accountID: [Number(req.params.accountid)],
          language: "eng_us"
        })
        .then(server2Reconstruct)
        .then(function (json) {
          res.setHeader('Content-Type', 'application/json');
          return res.send(json);
        }).catch(function (err) {
          console.log(err);
        });
      }
    });
  })

为了快速解释代码:我通过普通 Fetch 调用 server1 这个答案可能是 {},这是我遇到问题的地方。如果 accountid 不存在,服务器将返回一个 JSON 响应,并且没有错误可以抓取...

我应该怎么做才能抓住它......如果我抓住它切换到服务器 2。

(不要对 server2 调用感到困惑,因为它是另一个包)。

标签: node.jsjsonrest

解决方案


如果我正确理解您的问题,您应该按照以下步骤操作:

  • 获取初始 API
  • 调用.json()结果上的方法 - 返回一个承诺
  • 首先处理json响应.then(json => ...),这里检查结果是否{}然后调用server2,否则调用server1

顺便说一句,你的代码看起来很乱thencatch我建议把一些东西放入函数中,async/await如果可以的话,使用。

这是您可以使用的一些伪代码示例:

function server2Call() {
    return server2.fetchAccount({
        accountID: [Number(req.params.accountid)],
        language: 'eng_us'
    })
        .then(server2Reconstruct)
        .then(function (json) {
            res.setHeader('Content-Type', 'application/json');
            return res.send(json);
        }).catch(function (err) {
            console.log(err);
        });
}

app.get('/app/account/:accountid', function (req, res) {
    return fetch('https://server1.com/api/account/' + req.params.accountid)
        .then(res => {
            var contentType = res.headers.get('content-type');
            if (contentType && contentType.includes('application/json')) {
                return res.json();
            } else {
                server2Call()
            }
        })
        .then(json => {
            res.setHeader('Content-Type', 'application/json');
            if (json is {}) return server2Call()
            else return res.send(json);
        }).catch(function (err) {
            console.log(err);
        })
});

推荐阅读