gpt4 book ai didi

javascript - 从 JS 函数调用 NodeJS 函数

转载 作者:太空宇宙 更新时间:2023-11-04 02:45:38 25 4
gpt4 key购买 nike

我正在做一个基于 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 将我的文件夹设置为按服务器端和客户端文件的功能和公共(public)分隔

enter image description here

最佳答案

First initialize your HTML page with jQuery and on submitting the form send an Ajax request to the server as follows

$(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);
}
})

});
});

Create a route called contact in your NodeJS server and listen for the contact request with All parameters required for your need. In the following case am using an express server and body parser to parse the data from incoming request

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
})
}
});
});

In the above request am sending the name:as name, email: as email and message: as msg

关于javascript - 从 JS 函数调用 NodeJS 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51335396/

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