npm Запрос: Как обрабатывать редиректы? - PullRequest
0 голосов
/ 28 мая 2020

У меня были проблемы с запросом, который не выводил перенаправленную ссылку, когда вы получали ссылку gfycat от reddit, которая должна отправить вас в сеть gifdeliverynetwork. 1003 * здесь , но я не уверен, что должно произойти с переменной url. Я уже пытался изменить его на imgurl, но я новичок в javascript, поэтому я не понимаю, что здесь происходит.

вот что я сделал;

    if(cmd == `${prefix}rtt`){
        request("https://www.reddit.com/r/" + args + "/top/.json?t=all&limit=1", {
            method: 'HEAD',
            followAllRedirects: true
        }, function(err, response, body) {
            var url = response.request.href
        }) 
        request(url, {
            headers: {
              "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.46 Safari/537.36"
            },
          }, 
          function(err, response, body) { 
            let json = JSON.parse(body);
                try{
                    let imgurl = json["data"]["children"]["0"]["data"]["url"];
                    let title = json["data"]["children"]["0"]["data"]["title"];
                    let redditlink = json["data"]["children"]["0"]["data"]["permalink"];
                    if (imgurl.includes('gfycat')) {
                        let reEmbed = new Discord.RichEmbed()
                        .setColor(16711422)
                        .addField(
                            "rtt **" + args + "** requested by **" + message.author.tag + "**",
                            "[" + title + "](" + "https://reddit.com" + redditlink + ")", true
                            )
                        .setFooter(
                            "⚠️ Can't see the post? - Discord doesn't support most gfycat links but you can still click it!\n⚠️ To avoid gfycat don't use <r or <rtt ");
                        message.channel.send({ embed: reEmbed })
                        return message.channel.send(imgurl)
                    } else {
                        let reEmbed = new Discord.RichEmbed()
                        .setColor(16711422)
                        .addField(
                            "rtt **" + args + "** requested by **" + message.author.tag + "**",
                            "[" + title + "](" + "https://reddit.com" + redditlink + ")", true
                            )
                        message.channel.send({ embed: reEmbed })
                        return message.channel.send(imgurl)
                }}                        
                catch{
                    if (args === void(0)) {
                    let reEmbed = new Discord.RichEmbed()
                    .setColor(16711422)
                    .setTitle(
                        "⚠️ You must specify a subreddit!"
                    )
                    .setDescription(
                        "Use `<rm` if you would like to pull from a random subreddit"
                        )
                    return message.channel.send({ embed: reEmbed })
                    } else {
                        let reEmbed = new Discord.RichEmbed()
                    .setColor(16711422)
                    .setTitle(
                        "⚠️ Error getting data from " + args
                    )
                    .setDescription(
                        "Either this subreddit doesn't exist, or it might be empty"
                        )
                    return message.channel.send({ embed: reEmbed })
                    };                 
                }
            });
}

то, с чем мне нужна помощь, это бит

request("https://www.reddit.com/r/" + args + "/top/.json?t=all&limit=1", {
                method: 'HEAD',
                followAllRedirects: true
            }, function(err, response, body) {
                var url = response.request.href
            }) 
            request(url, {
                headers: {
                  "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.46 Safari/537.36"
                },
              }, 
              function(err, response, body) { 
 //here the body 
})

Я тоже пробовал

var options = {
            followRedirect: true,
            followAllRedirects: true,
            followOriginalHttpMethod: true
                  };
            request("https://www.reddit.com/r/" + args + "/top/.json?t=all&limit=1", options, function(err, response, body){ 

вот тут ошибка

(node:4696) UnhandledPromiseRejectionWarning: ReferenceError: imgurl is not defined
    at Client.<anonymous> (C:\Users\christian\Documents\GitHub\discordBot\index.js:171:21)
    at Client.emit (events.js:310:20)
    at MessageCreateHandler.handle (C:\Users\christian\Documents\GitHub\discordBot\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
    at WebSocketPacketManager.handle (C:\Users\christian\Documents\GitHub\discordBot\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:108:65)
    at WebSocketConnection.onPacket (C:\Users\christian\Documents\GitHub\discordBot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:336:35)
    at WebSocketConnection.onMessage (C:\Users\christian\Documents\GitHub\discordBot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:299:17)
    at WebSocket.onMessage (C:\Users\christian\Documents\GitHub\discordBot\node_modules\ws\lib\event-target.js:120:16)
    at WebSocket.emit (events.js:310:20)
    at Receiver.receiverOnMessage (C:\Users\christian\Documents\GitHub\discordBot\node_modules\ws\lib\websocket.js:789:20)
    at Receiver.emit (events.js:310:20)
(node:4696) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:4696) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...