gpt4 book ai didi

javascript - 第二种情况如何使用一段node js代码?

转载 作者:行者123 更新时间:2023-11-30 20:56:35 24 4
gpt4 key购买 nike

首先,让我更具体一点。我在我的网站上为联系页面设置了一个 nodemailer 代码,它工作得很好。但是,我有另一个页面,服务,我有另一种形式,并且想对该页面使用以前的设置代码,这样我就可以将提交的信息作为电子邮件发送。我尝试制作另一个文件并粘贴相同的代码,但将变量命名为 app2transporter2 等。但这是行不通的。我是 nodejs 开发的初学者,所以我需要帮助。实现这一目标的最佳方法是什么?

顺便说一句;联系人、服务页面和 app.js(nodejs 代码)文件位于根文件夹中。

Node js:

const express = require('express');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const path = require('path');
const nodemailer = require('nodemailer');

const app = express();

// View engine setup
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');

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

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

app.get('/', (req, res) => {
res.render('contact');
});

app.post('/send', (req, res) => {
const output = `
<ul>
<li>Name: ${req.body.name}</li>
<li>Email: ${req.body.email}</li>
<li>Phone: ${req.body.phone}</li>
</ul>
`;

// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
service: 'gmail',
port: 25,
secure: false, // true for 465, false for other ports
auth: {
user: 'email', // senders email
pass: 'password' // senders password
},
tls:{
rejectUnauthorized:false
}
});

// setup email data with raw html
let mailOptions = {
from: '"xyz" <xyz@info.com>', // sender address
to: req.body.email, // receiver or receivers
subject: 'xyz', // Subject line
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('contact', {msg:'Your contact message has successfully sent to us.'});
});
});

app.listen(3000, () => console.log('Server started...'));

最佳答案

为什么,你创建了一个模块。 https://nodejs.org/api/modules.html

//yourModule.js
const sendMail = (email, output) => new Promise((resolve, reject) => {
//your code to send mail.
//resolve the promise
})

module.exports { sendMail }

然后你把它包含在你需要的地方:

const emailModule = require('myModuleName');

emailModule.sendMail('some@mail.com', output).then(() => {
//whatever
}).catch(catchErrFn)

关于javascript - 第二种情况如何使用一段node js代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47599404/

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