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

标签 json node.js get request discord.js

我正在使用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/

相关文章:

node.js - 尽管使用 err.stack,但获取 "at Error (native)"而不是实际的 node.js 堆栈跟踪

python - 在不使用 python 请求模块的情况下进行此 API 调用的最佳替代方法是什么?

mysql - 对数据库表的行进行排序

php - MySQLI_ASSOC 转 JS 数组

javascript - 将附加参数传递给 Node js 中 fs.readFile 的回调

node.js - Azure updateEntity - 无法读取未定义的属性(读取 'replace' )[Node.js]

php - 如何使用带参数的字符串从 mySQL 获取数据?

javascript - 如何从 .t​​hen() 以 Angular 返回对函数的响应?

json - 如何在Dart中定义一个属性可以为null或另一个模型的模型

javascript - 如何遍历所有可能的 JSON 对象键对一次?