javascript 需要做验证,以便如果网址无效,然后只发送电子邮件

xt0899hw  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(79)

我已经创建了一个脚本来检查一系列的网址,如果他们的http状态码是200,那么网址是向上的,如果他们的http状态码不是200,那么他们是向下的。
我也用nodemailer设置了一个邮件功能,它会发送一个失效的url列表,但是现在的问题是如果所有的url都是有效的,那么它也会发送空邮件。
我想做的是,只有发送邮件,如果网址是无效的/向下的网址,如果所有的网址都是有效的,然后发送任何其他消息,如“没有无效的网址”或只是不发送任何电子邮件,并退出脚本。

const request = require("request");
const nodemailer = require("nodemailer");

// list of urls that need to be checked
const urlList = [
  // valid url (returns http 200)
  "https://google.com/",
  // invalid url (returns http 404 not found)
  "https://googglslfdkfl.com/",
];

// e-mail setup
const transporter = nodemailer.createTransport({
  host: "smtp.gmail.com",
  port: 587,
  auth: {
    user: "email",
    pass: "password",
  },
  secure: false,
});

//get the http status code
function getStatus(url) {
  return new Promise((resolve, reject) => {
    request(url, function (error, response, body) {
      resolve({
        site: url,
        status:
          !error && response.statusCode == 200
            ? "OK"
            : "Down: " + error.message,
      });
    });
  });
}

let promiseList = urlList.map((url) => getStatus(url));

// return a list of only the sites in an array with status of Down
const returnListOfUrls = Promise.all(promiseList).then((resultList) => {
  const listWithDownStatus = resultList
    .map((result) => result.status.startsWith("Down") && result.site)
    .filter(Boolean);
  return listWithDownStatus;
});

const runNodeMailer = () => {
  returnListOfUrls.then((res) => {
    const message = {
      from: "from-email",
      to: "to-email",
      subject: "test",
      html: `<h1>Following URLs have issues:</h1>
              <p>${res.join(", ")}</p>`,
    };

    console.log(res, "---", message);
    transporter.sendMail(message, function (err, info) {
      if (err) {
        console.log(err);
      } else {
        console.log(info);
      }
    });
  });
};

runNodeMailer();
2jcobegt

2jcobegt1#

如果我很好地理解了你的问题,那么你应该检查你从returnListOfUrls中获得的资源,并根据这些资源决定你要发送什么消息。
代码如下所示:

const runNodeMailer = () => {
  returnListOfUrls.then((res) => {
  
  let htmlMessage = ''
  
  if(res.length > 0) {
     htmlMessage = `<h1>Following URLs have issues:</h1>
                    <p>${res.join(", ")}</p>`
  } else {
      htmlMessage = `<h1>You have no issues with urls</h1>`             }
      
    const message = {
      from: "from-email",
      to: "to-email",
      subject: "test",
      html: htmlMessage,
    };

    console.log(res, "---", message);
    transporter.sendMail(message, function (err, info) {
      if (err) {
        console.log(err);
      } else {
        console.log(info);
      }
    });
  });
};

或者,如果您不想发送任何消息,请执行以下操作:

if(res.length > 0) {
     htmlMessage = `<h1>Following URLs have issues:</h1>
                    <p>${res.join(", ")}</p>`
  } else {
     return
}

相关问题