我正在使用node.js(和discord.js)来制作一个discord 机器人。
我正在使用带有 npm 请求模块的 GET 请求。当用户输入“!cat”时,代码按预期工作,它从 https://aws.random.cat/meow 获取数据并发布一张猫图片,但是有时服务器会给出 403 禁止错误,导致生成 HTML 页面而不是 JSON,并由于意外 token 而导致机器人崩溃。
我正在寻找一种方法来检测 HTML 页面并停止代码/发布错误消息,方法是检测端点是 HTML 而不是 JSON,或者发送回的数据内容:
- JSON =
{ file: 'https://catlink.jpg' }
- HTML 403 =
<!DOCTYPE HTML PUBLIC...
IMG1: Error - HTML page response, IMG2: Expected responses 1 per request
我当前的代码块如下:
//RANDOM CATS
if(command === "cat" || command === "meow"){
//Connection options
var catoptions = {
url: "https://aws.random.cat/meow",
headers: {
'Content-Type': 'application/json',
'Accept': 'application.json'
}
};`
//Send the request
let request = require("request");
request(catoptions, function(err, response, body){
if(err){
console.log("error code #002");
} else {
//Receive the body of the JSON
var catresult = JSON.stringify(body); //stringify incase page returns HTML 403 error - Will recieve "<!DOCTYPE HTML PUBLIC..." as first bit of data
console.log(catresult) //Send to log to see if JSON "cat pic" data is returned or the HTML 403 error
let meowdata = JSON.parse(body);
//Responbse body
let meowpic = meowdata.file;
console.log(meowpic); //Send link to console
message.channel.send(meowpic); //Send link to discord channel with discord.js
}
});
} //END OF RANDOM CATS
最佳答案
JSON.parse
如果传递了无效的 JSON,并且 HTML 不是有效的 JSON,则抛出异常,您必须捕获异常以避免崩溃。
来自docs :
Throws a SyntaxError exception if the string to parse is not valid JSON.
request(catoptions, function(err, response, body) {
if (err) {
console.log("error code #002");
} else {
try {
//Receive the body of the JSON
let catresult = JSON.stringify(body); //stringify incase page returns HTML 403 error - Will recieve "<!DOCTYPE HTML PUBLIC..." as first bit of data
console.log(catresult) //Send to log to see if JSON "cat pic" data is returned or the HTML 403 error
let meowdata = JSON.parse(body);
//Responbse body
let meowpic = meowdata.file;
console.log(meowpic); //Send link to console
message.channel.send(meowpic); //Send link to discord channel with discord.js
} catch (e) {
console.error(e);
}
}
});
关于json - Node.js GET 请求有时会收到 HTML 文档而不是 JSON 并崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50607502/