【问题标题】:NODEJS How do I perform an action when URL response status is 404?NODEJS URL 响应状态为 404 时如何执行操作?
【发布时间】:2020-09-17 10:05:22
【问题描述】:

我正在制作一个不和谐的机器人,我想制作一个发送 3 个随机字符的命令,然后将这些字符放在 url 的末尾以检查它是否存在(在这种情况下,我使用 steam 帐户来检查id 被占用),但我需要这样做,以便当响应状态为 404 时,它会发送一条消息说 ID 未被占用。

var urlExists = require('url-exists');

      //3CHAR
   else if (message.content == "+3char") {     
     message.channel.send(getRandomString(3));


   var theURL = "https://steamcommunity.com/id/" + message.channel.lastmessage;

         urlExists("theURL");



      if (response.status != 404) {     
      return;

    }


    else {message.channel.send("`URL is not taken`");}


}

这就是我现在所拥有的,但是我收到错误“未定义响应”。 任何建议将不胜感激!

【问题讨论】:

    标签: node.js url discord.js httpresponse steam


    【解决方案1】:

    您遇到了async 问题。您需要将回调函数传递给urlExists。一旦urlExists 对象执行完毕,回调函数就会执行。

    https://www.npmjs.com/package/url-exists

    var urlExists = require('url-exists');
    
    urlExists('https://www.google.com', function(err, exists) {
      console.log(exists); // true
    });
    
    urlExists('https://www.fakeurl.notreal', function(err, exists) {
      console.log(exists); // false
    });
    

    在你的情况下,你想做一些事情:

    var urlExists = require('url-exists');
    
    var theURL = "https://steamcommunity.com/id/" + message.channel.lastmessage;
    
    urlExists("theURL", (err, exists) => {
      if (err) {
        // handle error
      }
    
      if (exists) {
        message.channel.send("`URL is not taken`");
      } else {
        // do something when the URL does not exist
      }  
    });
    

    【讨论】:

    • 只是为了澄清它的作用是当找不到 URL 页面时它会发送一条消息,对吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多