Nodemailer无法在routes文件夹中运行

时间:2018-05-25 16:58:31

标签: javascript node.js express nodemailer

我有一个问题,如果我从app.js调用它的快速服务器定义,我的订阅表格是完美的,但如果我将subscribe.js移动到路径文件夹,我不能发送邮件。我连接了两个文件,但仍然无法正常工作。当我按下发送按钮时,它给出了错误“Not Found”(localhost:3000 / send)

这是我的app.js代码

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var ejs = require('ejs');

var indexRouter = require('./routes/index');
var subscribeRouter = require('./routes/subscribe');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/subscribe', subscribeRouter);

module.exports = app;

和我的subscribe.js代码

var express = require('express');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');

var router = express.Router();

/* GET Subscribe Page. */
  router.get('/', (req, res) => {
  res.render('subscribe');
});

// Body Parser Middleware
router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());

router.post('/send', (req, res) => {
  const output = `
    <p>....</p>
    <h3>...</h3>
    <ul>  
        <li>E-naslov: ${req.body.email}</li>
    </ul>
  `;

// create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    host: '...'
    port: 465,
    secure: true, // true for 465, false for other ports
    auth: {
        user: 'example@example.com', // generated ethereal user
        pass: 'xxxxxxxx'  // generated ethereal password
    },
    tls:{
      rejectUnauthorized:false
    }
  });

// setup email data with unicode symbols
  let mailOptions = {
      from: '"blabla"<info@blabla.com>', // sender address
      to: 'example@gmail.com', // list of receivers
      subject: 'Novo naročilo na e-novice', // Subject line
      text: 'Hello world?', // plain text body
      html: output // html body
  };

// send mail with defined transport object
  transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
          return console.log(error);
      }
      console.log('Message sent: %s', info.messageId);   
      console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));

      res.render('subscribe', {msg:'Email has been sent'});
  });
});

module.exports = router;

在我的subscribe.ejs中,我的表单有action = / send和method = post

2 个答案:

答案 0 :(得分:1)

我认为您的路线实际上是/ subscribe / send

当你在索引中使用订阅路由器时,你将它映射到/ subscribe,并且路由器/ send是相对的。

答案 1 :(得分:1)

使用

app.use(subscribeRouter);

而不是

app.use('/send', subscribeRouter);

<强>更新

我已更改上面的代码以使用路由/send并确保您的views目录中存在subscribe.ejs