有一个节点 JS 脚本(app.js),用于向邮件发送一封信:
const { response } = require("express");
const express = require("express");
const nodemailer = require("nodemailer");
const app = express();
const port = 5000;
//
function sendEmail(tel) {
return new Promise((resolve, reject) => {
var tranporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: ,
pass: ,
},
});
const mail_configs = {
from: "myEmail",
to: "artemdvd@mail.ru",
subject: "Testing Koding 101 Email",
text: "tel",
};
tranporter.sendMail(mail_configs, function (error, info) {
if (error) {
console.log(error);
return reject({ message: "An error has occured" });
}
return resolve({ message: "Email sent succesfuly" });
});
});
}
app.get("/", (req, res) => {
sendEmail()
.then((response) => res.send(response.message))
.catch((error) => res.status(500).send(error.message));
});
app.listen(port, () => {
console.log(`nodemailerProject is listening at http://localhost:${port}`);
});
其他js文件中有一个按钮,它运行这个js脚本并在我按下按钮时发送电子邮件:
let input = document.getElementById("phonenumber");
head.addEventListener("click", function () {
fetch("http://localhost:5000/")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
});
html 文件中有一个用于文本消息的输入字段
<input id="phonenumber" class="text-order" type="text"
placeholder="___________"'/>
如何在按下按钮时通过电子邮件发送此输入值?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
Fetch API 接受第二个参数,一个选项对象。这是您传递输入的地方。在您的情况下,您需要捕获输入的值。所以如果你有:
let input = document.getElementById("电话号码");那么您应该能够使用
input.value访问该值。如果您在选项对象的 body 属性中发送它,它应该显示在服务器上的请求正文中。类似这样的事情:
fetch("http://localhost:5000/", { body: JSON.stringify(input.value) })我发现您还在监听另一个元素(
head)的点击。如果是这种情况,那么您可能需要在输入上使用onChange处理程序,该处理程序将值存储在本地某处。然后,当用户单击另一个元素时,您就可以将其传递到获取选项中。这是发送选项的语法示例(借自我上面共享的文档),演示了它将接受的不同选项:
// Example POST method implementation: async function postData(url = '', data = {}) { // Default options are marked with * const response = await fetch(url, { method: 'POST', // *GET, POST, PUT, DELETE, etc. mode: 'cors', // no-cors, *cors, same-origin cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', // include, *same-origin, omit headers: { 'Content-Type': 'application/json' // 'Content-Type': 'application/x-www-form-urlencoded', }, redirect: 'follow', // manual, *follow, error referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url body: JSON.stringify(data) // body data type must match "Content-Type" header }); return response.json(); // parses JSON response into native JavaScript objects } postData('https://example.com/answer', { answer: 42 }) .then((data) => { console.log(data); // JSON data parsed by `data.json()` call });