有一個節點 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="___________"'/>
如何在按下按鈕時透過電子郵件發送此輸入值?
P粉4941519412024-03-31 11:39:54
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 });