Nodemailer 不适用于路由文件夹

Nodemailer doesn't work from routes folder

我遇到一个问题,如果我从定义了快速服务器的 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

我觉得你的路线其实是/subscribe/send

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

使用

app.use(subscribeRouter);

而不是

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

更新

我已将上面的代码更改为使用路由 /send 并确保 subscribe.ejs 存在于您的视图目录中