通过按钮调用函数

Function call via the button

我编写了将电子邮件发送到 node.js 的代码,它们在不同的文件中:

mail.js

require('dotenv').config()
const nodemailer = require('nodemailer')

let transporter = nodemailer.createTransport({
  host: 'smtp.mail.ru',
  port: 465,
  secure: true,
  auth: {
    user: process.env.EMAIL,
    pass: process.env.PASSWORD,
  },
})

const mailOptions = {
    from: 'Mailer Test <>',
    to: '<>',
    subject: ''
}

transporter.sendMail(mailOptions)

和按钮:

script.js

let submitButton = document.querySelector('.submit_button');
submitButton.addEventListener('click', function(e) {
    
})

如何在按钮中调用执行mail.js?

mail.js在服务器环境下执行,客户端(浏览器)无法访问。在 HTML 页面上,您的 script.js 可能是 运行。前端(浏览器)无法直接访问后端。

我建议设置一个 Express 服务器和发送邮件的路由。

下载快递(和body-parser)包:

npm install express body-parser

# or

yarn add express body-parser

创建一个名为 index.js 的文件,并设置一个基本的 express 服务器:

const bodyParser = require('body-parser');
const express = require('express');
const app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.listen(3000, () => {
    console.log('App is listening on port 3000!');
});

正文解析器允许您解析正文或 URL 中的数据,例如函数参数。

接下来,我们告诉应用程序监听端口 3000 上的连接。该应用程序将等到收到连接,然后决定下一步做什么。

现在,我们可以添加一条路线。路线是一个端点,或 URL 中的一个位置 例如: https://google.com/search 将是 /search 路线 将是 /questions/1234 路线

我们将添加 /mail 路由,并接收两个参数:tosubject。您的客户将在发送请求时指定此项。

然后,我们将执行 mail 函数,这将是您的 mail.js 代码。

const bodyParser = require('body-parser');
const express = require('express');
const app = express();

require('dotenv').config()
const nodemailer = require('nodemailer')

function mail(to, subject) {
    const transporter = nodemailer.createTransport({
      host: 'smtp.mail.ru',
      port: 465,
      secure: true,
      auth: {
        user: process.env.EMAIL,
        pass: process.env.PASSWORD,
      },
    });

    const mailOptions = {
        from: 'Mailer Test <>',
        to: to,
        subject: subject
    }

    transporter.sendMail(mailOptions)
}

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get('/mail', (req, res) => { // The req variable is the request, or the data, and the res variable is the response that you send back.
    const query = req.query; // The URL encoded data that your HTML page will send
    const to = query.to; // you will specify these in the HTML page
    const subject = query.subject;

    mail(to, subject);
});

app.listen(3000, () => {
    console.log('App is listening on port 3000!');
});

使用 node index.js 启动您的服务器。

现在,在您的 script.js 中,您可以向 URL 发送一个 ajax requestlocalhost:3000/mail?to=test@gmail.com&subject=Subject!

编码愉快!