javascript - 从 JS 函数调用 NodeJS 函数
问题描述
我正在做一个基于 firebase 的项目,我需要链接一个将电子邮件发送到客户端脚本的服务器端函数。
这是我的服务器端 index.js 文件
const functions = require('firebase-functions');
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'xxx@gmail.com',
pass: 'password'
}
});
var mailOptions = {
from: 'xxx@gmail.com',
to: 'xxx@gmail.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
我想知道如何让 html 中的按钮调用脚本中将调用 transporter.sendMail 的函数。我以前从未接触过node js,所以请原谅我缺乏知识。
如果这有助于firebase将我的文件夹设置为按功能分隔,并为服务器端和客户端文件公开
解决方案
首先使用表单初始化您的 HTML 页面,
jQuery
并在提交表单时向服务器发送Ajax
请求,如下所示
$(document).ready(function() {
$("#formoid").submit(function(event) {
event.preventDefault();
$.ajax({
url: 'http://xxxxxxx.com/contact', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#formoid").serialize(), // post data || get data
success : function(result) {
$('#formoid')[0].reset();
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
创建一个
contact
在您的NodeJS
服务器中调用的路由,并使用您需要的所有参数侦听联系请求。在以下情况下,我使用express server
andbody parser
来解析来自传入请求的数据
app.post('/contact', (req, res) => {
var transporter = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "xxxxx",
pass: "xxxxx"
}
});
var mailOptions = {
from: req.body.email,
to: 'xxxxx@xx.com',
subject: 'Contact form',
text: 'From: ' + req.body.name + '\n Email: ' + req.body.email + '\nMessage: ' + req.body.msg
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
res.status(500).json({
message: "Error",
error: error
})
} else {
res.status(200).json({
message: "Its working",
response: info.response
})
}
});
});
在上述请求中,我正在发送
name:as name
,email: as email
和message: as msg
推荐阅读
- php - PHP 在数据库上运行存储过程,如何在不更改源代码的情况下查看传入的具体参数?
- postgresql - 从 Oracle 到 PostgreSQL 的加解密
- reactjs - 在 React 组件中使用 botframework-webchat 的正确方法(使用 create-react-app)?
- c# - 根据选择不同的组合框更改组合框中的显示
- python - Python 项目不会根据 sys.path 顺序获取依赖项
- dart - Dart:实例变量在私有类中应该是私有的还是公共的?
- javascript - 删除 HTML 页面中使用的 javascript 文件中未使用的代码?
- mysql - 如何将查询结果保存在变量中并在另一个查询中使用
- javascript - 从html文件打开时,如何让Javascript从html内部运行
- asp.net-mvc - 拒绝访问路径“C:\inetpub\wwwroot\App_Data\TEMP\PluginCache”。亚马逊 AWS 豆茎