Node.js GET 请求有时会收到 HTML 文档而不是 JSON 并崩溃

Node.js GET request sometimes receives HTML document instead of JSON and crashes

我正在使用 node.js(和 discord.js)制作一个 discord 机器人。

我正在使用带有 npm 请求模块的 GET 请求。当用户键入“!cat”时,代码按预期工作,它从 https://aws.random.cat/meow 获取数据并发布猫图片,但是有时服务器会给出 403 禁止错误,导致 HTML 页面而不是 [=42] =] 并由于意外令牌导致机器人崩溃。

我正在寻找一种方法来检测 HTML 页面并通过检测端点是 HTML 而不是 JSON 来停止 code/post 错误消息,或发回的数据内容为:

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);
        }
    }
});