Nodemailer - 重定向到成功页面

时间:2018-03-05 00:48:55

标签: javascript node.js express nodemailer

尝试在发送电子邮件后让我的页面从node.js和express.js页面重定向。消息被发送,我在我的终端中获取console.log()(使用morgan进行日志记录),但它没有将我重定向到成功页面,而且我没有在浏览器中收到console.log错误。它只是停滞,然后我得到一个localhost没有发送任何数据错误。以前从未使用过nodemailer但我设法收到了发送的消息,我只是在重定向到新页面时出现问题。

谢谢!

//成功HTML代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

    <h1>Success</h1>

  </body>
</html>

//表格框

  <form action="/contact" id="contact-form" method="post" role="form">
    <fieldset>
      <label for="name">Name &#42;</label>
      <input id="name" name="name" type="text" placeholder="Your name" required="required">
      <label for="email">Email &#42;</label>
      <input id="email" name="email" type="text" placeholder="Your email" required="required">
      <label for="message">Message &#42;</label>
      <textarea id="message" name="message" placeholder="Enter your message here" rows="3" required="required"></textarea>
      <button type="submit">Submit</button>
    </fieldset>
  </form>

//成功HTML路线

 app.get('/success', function(req,res){
  res.sendFile(__dirname + '/views' + '/success.html');
});

// nodemailer //来自联系表格的POST路线

app.post('/contact', function (req, res) {
  let mailOpts, smtpTrans;
  smtpTrans = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    auth: {
      user: process.env.GMAIL_USER,
      pass: process.env.GMAIL_PASS
    }
  });
  mailOpts = {
    from: req.body.name + ' &lt;' + req.body.email + '&gt;',
    to: process.env.GMAIL_USER,
    subject: 'New message from Portfolio site',
    text: `${req.body.name} (${req.body.email}) says: ${req.body.message}`
  };
  smtpTrans.sendMail(mailOpts, function (error, res) {
    if (error) {
      return console.log(error);
    }
    else {
      console.log('success');
      res.redirect('/success');
    }
  });
});

1 个答案:

答案 0 :(得分:0)

想知道您是否仍然坚持这个问题,但以防万一,以下对我有用。

app.post('/contact', function (req, res) {
  let mailOpts, smtpTrans;
  smtpTrans = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    auth: {
      user: process.env.GMAIL_USER,
      pass: process.env.GMAIL_PASS
    }
  });
  mailOpts = {
    from: req.body.name + ' &lt;' + req.body.email + '&gt;',
    to: process.env.GMAIL_USER,
    subject: 'New message from Portfolio site',
    text: `${req.body.name} (${req.body.email}) says: ${req.body.message}`
  };
  smtpTrans.sendMail(mailOpts, function (error, res) {
    if (error) {
      return console.log(error);
    }
    else {
      console.log('success');
      // NOT HERE res.redirect('/success');
    }
  });
  res.redirect('/success'); // I MOVED THE REDIRECTING CODE HERE AND WORKED
});