gpt4 book ai didi

javascript - Nodemailer 无法在路由文件夹中工作

转载 作者:行者123 更新时间:2023-12-01 02:01:29 25 4
gpt4 key购买 nike

我遇到一个问题,如果我从定义了 Express 服务器的 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 是相对的。

关于javascript - Nodemailer 无法在路由文件夹中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50533839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com