首页 > 解决方案 > 从 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将我的文件夹设置为按功能分隔,并为服务器端和客户端文件公开

在此处输入图像描述

标签: javascriptnode.jsfirebaseemail

解决方案


首先使用表单初始化您的 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 serverandbody 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 emailmessage: as msg


推荐阅读