node.js - 如何捕获来自 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 调用感到困惑,因为它是另一个包)。
解决方案
如果我正确理解您的问题,您应该按照以下步骤操作:
- 获取初始 API
- 调用
.json()
结果上的方法 - 返回一个承诺 - 首先处理json响应
.then(json => ...)
,这里检查结果是否{}
然后调用server2,否则调用server1
顺便说一句,你的代码看起来很乱then
,catch
我建议把一些东西放入函数中,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);
})
});
推荐阅读
- tensorflow - Keras 自定义单元格无效参数:您必须为占位符张量提供值
- python - 在 Linux 上的 Wine 中安装 Python:安装程序中止并出现“拒绝访问”错误
- coq - 如何实现 Coq?
- histogram - 在 Spotfire 中仅包含带有 AutoBinNumeric() 的特定行
- c - 为什么 if 条件总是为真?
- flutter - 在特定时间播放低音和高音音频并在音高之间转换
- xcode11 - 存档构建因特定的 Swift 包管理器库而失败
- r - R重命名许多CSV中的列
- java - 使用 Python 获取 API - 超时问题
- google-cloud-dataprep - 无法合并两个数据集