Express get method not calling first function

Viewed 28

So I am writing some code to send me a email when someone visits my website. Here is the code I have

app.get("/", function(req, res, next) {
  var mailOptions = {
    from: 'removed for obvious reasons',
    to: 'removed for obvious reasons',
    subject: 'User visited',
    text: 'A user has visited your site'
  };

  transporter.sendMail(mailOptions, function(error, info){
    if (error) {
      console.log(error);
    } else {
      console.log('Email sent: ' + info.response);
    }
  });
  console.log("User visited");
  next();
}, function(req, res) {
  res.sendFile( path.join( __dirname, "client-files", "index.html" ));
});

But when I visit my website then I get nothing. I don't get a email and nothing's printed out, I just get the web page. Does anyone know how to fix this?

1 Answers

Looks like the problem is async code. In short: The order of the code is not the order it gets executed.

It takes time to send that mail. NodeJS is single-threaded it sends the email and then continues on with the code.

So it sends the email and calls next function right away and sends the user to the next handler, without knowing anything about the email.

I can't find a real good reason to have two different handlers.

Version 1: Don't wait for email, send the page right away


app.get("/", function(req, res, next) {
  var mailOptions = {
    from: 'removed for obvious reasons',
    to: 'removed for obvious reasons',
    subject: 'User visited',
    text: 'A user has visited your site'
  };

  transporter.sendMail(mailOptions, function(error, info){
    if (error) {
      console.log(error);
    } else {
      console.log('Email sent: ' + info.response);
    }
  });

  console.log("User visited");

  res.sendFile( path.join( __dirname, "client-files", "index.html" ));
});

Result: It will

  1. Log out 'user visited'
  2. Send file page
  3. Send email
  4. Log out 'Email sent'

Version 2: Wait for email


app.get("/", function(req, res, next) {
  var mailOptions = {
    from: 'removed for obvious reasons',
    to: 'removed for obvious reasons',
    subject: 'User visited',
    text: 'A user has visited your site'
  };

  transporter.sendMail(mailOptions, function(error, info){
    if (error) {
      console.log(error);
    } else {
      console.log('Email sent: ' + info.response);
      console.log("User visited");
      res.sendFile( path.join( __dirname, "client-files", "index.html" ));
    }
  });
});

Result: It will

  1. Send email
  2. Log out 'Email sent'
  3. Log out 'User visited'
  4. Send file
Related