Javascript Api-页面可';找不到
我正在从API请求一些数据,尤其是Javascript Api-页面可';找不到,javascript,node.js,api,node-fetch,Javascript,Node.js,Api,Node Fetch,我正在从API请求一些数据,尤其是https://api.tvmaze.com/singlesearch/shows?q=Friends&embed=episodes通常,当我用API收到无效请求时,我会以JSON格式得到它。因此,我可以轻松地将数据发送回(discord)。但是使用此API,如果您用随机字符串替换朋友,它将返回一个页面,显示此API.tvmaze.com页面无法找到。如何将此数据发送回用户 我使用NodeJS和节点获取模块来获取请求 fetch('https://api.tvm
https://api.tvmaze.com/singlesearch/shows?q=Friends&embed=episodes
通常,当我用API收到无效请求时,我会以JSON格式得到它。因此,我可以轻松地将数据发送回(discord)。但是使用此API,如果您用随机字符串替换朋友
,它将返回一个页面,显示此API.tvmaze.com页面无法找到
。如何将此数据发送回用户
我使用NodeJS和节点获取
模块来获取请求
fetch('https://api.tvmaze.com/singlesearch/shows?q=' + msg + '&embed=episodes') //msg is the users input
.then(function(res) {
return res.json();
}).then(function(json) {
console.log(json.network.name) // if input is friends this returns NBC
});
因此,我对node fetch不是100%熟悉,但我认为您可以在.then()函数中检查res的状态
fetch('https://api.tvmaze.com/singlesearch/shows?q=' + msg + '&embed=episodes') //msg is the users input
.then(function(res) {
if(res.status === 404) {
//HANDLE THE 404 Page Not Found
} else {
return res.json();
}
}).then(function(json) {
console.log(json.network.name) // if input is friends this returns NBC
});
我不熟悉您正在使用的确切库,但是在检查响应主体之前,您可以检查状态。找不到的页面是404,在这种情况下,你可以创建一个对象来恢复你的自我。换句话说,检查一下解析json是否失败。如果它真的失败了,实现任何你想要的行为以防失败。@Ken我该如何检查它呢?例如,如果是JSON响应,我通常会执行
(如果JSON.error==404)
,但这当然不是JSON响应,我如何检查状态?您能否编辑问题以包含调用API的代码?如果我能看到你是如何处理的,我可以帮你更好。