1

I have written this code using node-mailer to send mail. When I start the server in cmd and go to localhost:8080, it sends to mail two times. Why this is so?

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);
rishiag
  • 2,248
  • 9
  • 32
  • 57

1 Answers1

3

When you want to open a page in a browser, it usually sends two requests to the server, one for fetching the favicon.ico and another one for the page it self.

fardjad
  • 20,031
  • 6
  • 53
  • 68