我有一个简单的节点应用程序,它包含一个表单,该表单使用nodemailer通过POST通过电子邮件发送其数据。
HTML
<form accept-charset="UTF-8" action="/" method="POST" class="contact-form">
<input type="text" name="name" placeholder="NAME" required>
<input type="email" name="email" placeholder="EMAIL" required>
<textarea name="message" placeholder="MESSAGE" required></textarea>
<button name="send" type="submit">SEND</button>
</form>
Js(在我的index.js中)
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'nodemailersampleemail@gmail.com',
pass: 'foopassword'
}
});
app.post('/', function (req, res) {
response = {
name: req.body.name,
email: req.body.email,
message: req.body.message
};
var mailClient = {
from: 'nodemailersampleemail@gmail.com',
to: 'nodemailersampleemail@gmail.com',
subject: `Message from ${response.name}`,
text: `Name: ${response.name}\nEmail: ${response.email}\nMessage:${response.message}`
};
transporter.sendMail(mailClient, function (error, info) {
if (error) {
console.log(error);
} else {
res.redirect("/success.html");
}
});
})
我将整个(最小化)应用上传到github,如果需要澄清我的应用如何运作:https://github.com/agreyfield91/Nodemailer-Firebase-App
我正在尝试将此部署到firebase,但是由于支持由于某种原因我得知,firebase SDK不支持POST。我被告知我必须在链接到函数的html中使用onsubmit
才能使我的应用程序正常工作,如下所示:
<form accept-charset="UTF-8" class="contact-form" onsubmit="sendData(); return false;">
<input type="text" name="name" placeholder="NAME" id="formName" required>
<input type="email" name="email" placeholder="EMAIL" id="formEmail" required>
<textarea name="message" placeholder="MESSAGE" id="formMessage" required></textarea>
<button name="send" type="submit">SEND</button>
</form>
我遇到的问题是我似乎无法正确链接功能。我写了一个sendData()函数,放在我的index.js文件中,如下所示(我的传输变量在函数之外):
function sendData(){
response = {
name: document.getElementById('formName').value,
email: document.getElementById('formEmail').value,
message: document.getElementById('formMessage').value
};
var mailClient = {
from: 'nodemailersampleemail@gmail.com',
to: 'nodemailersampleemail@gmail.com',
subject: `Message from ${response.name}`,
text: `Name: ${response.name}\nEmail: ${response.email}\nMessage:${response.message}`
};
transporter.sendMail(mailClient, function (error, info) {
if (error) {
console.log(error);
} else {
res.redirect("/success.html");
}
});
}
但是当我提交时,页面刷新并且表单数据被插入到url中(确切地说,当根本没有任何功能时会发生什么)。因此,要么没有调用函数,要么我在函数内部写的函数没有做任何事情。我做错了什么?