我目前正在使用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,这个答案可能是{},这是我遇到的问题。如果该帐户ID不存在,则服务器将返回一个没有错误的JSON响应...
我应该怎么做才能捕获它...如果发现它,请切换到服务器2。
(不要对server2调用感到困惑,因为它是另一个软件包)。
答案 0 :(得分:2)
如果我正确理解了您的问题,则应按照以下步骤操作:
.json()
方法-该方法返回一个诺言.then(json => ...)
中处理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);
})
});