为什么我的代码发送邮件两次?

时间:2014-09-10 05:05:08

标签: javascript node.js

我使用node-mailer编写此代码来发送邮件。当我在cmd中启动服务器并转到localhost:8080时,它会发送两次邮件。为什么会这样?

var http = require('http');
var edge = require('edge');
var port = process.env.PORT || 8080;

var params = {
    connectionString: "Data Source=localhost;Initial Catalog=node-test;Integrated Security=True",
    source: "SELECT * FROM emailtable"
};
var nodemailer = require("nodemailer");

var smtpTransport = nodemailer.createTransport("SMTP",{
   service: "Gmail",
   auth: {
       user: email,
       pass: password
   }
});
var getTopUsers = edge.func('sql', params);


function logError(err, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.write("Error: " + err);
    res.end("");
}   
var minutes = 1, the_interval = minutes * 60 * 1000;
var emailText = "";
http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    //setInterval(function() {
    getTopUsers(null, function (error, result) {
        emailText=""
        if (error) { logError(error, res); return; }
        if (result) {
            res.write("<ul>");
            result.forEach(function(user) {
                res.write("<li>" + user.emails + "</li>");
                emailText = emailText + user.emails + " ";
                //console.log(emailText);
            });

            res.end("</ul>");

        }
        else {
        }
        console.log("just mailed")
smtpTransport.sendMail({
   from: email, // sender address
   to: email, // comma separated list of receivers
   subject: "Hello", // Subject line
   text: emailText // plaintext body
}, function(error, response){
   if(error){
       console.log(error);
   }else{
       console.log("Message sent: " + response.message);
   }
});
    });
    //}, the_interval);

}).listen(port);



    console.log("Node server listening on port " + port);

1 个答案:

答案 0 :(得分:3)

如果您想在浏览器中打开一个页面,它通常会向服务器发送两个请求,一个用于获取 favicon.ico ,另一个用于自己的页面。