ノード、エクスプレス、nodemailer、およびTailWindCSSとの接触フォームを作成します.
34341 ワード
あなたのポートフォリオ、会社のウェブサイト、または任意の他のウェブサイトの場合は、機能的な連絡先フォームが良い印象を残しても、あなたのアカウントに電子メールを送信するプロセスを自動化する上で作業することがあります.畝
このチュートリアルでは、ノード、Express、NodeDailerとTailWindCSSを使用して連絡フォームを作成する方法を示します.フォームの応答を受け入れるためのカスタムルートを設定し、HTMLファイルをブラウザに提供し、TailWindCSSを使用してフォームとスタイルに機能を追加します.畝
NODEJSはあなたのシステムにインストールされます.そうでない場合は、here .畝 HTMLとCSSの基本的な理解. 表現の基本的理解.畝 コードに直接スキップする場合は、このプロジェクトへのGithub Repoリンクです.
https://github.com/Kunal-Keshan/node-express-nodemailer-tailwindcss-contact-form
飛び込みましょう!畝
新しいプロジェクトを作成します.電話します NPM INIT - Yを実行してノードプロジェクトを起動します. 次の依存関係をプロジェクトにインストールします.
畝
畝
TailWindCSS、PostCSS、およびAutoPrefixerは、我々のプロジェクトでTailwindクラスを使用できるようにする開発依存関係です.
畝
nodemonと同時に、新しい変更(nodemon)があるときにサーバーが再起動し、複数のスクリプトを同時に実行できるようにする開発依存関係です. 次のスクリプトをパッケージに追加します.JSON
このプロジェクトには3つの部品が必要です.リクエストハンドラー、メールを送信する機能とフロントエンド機能を備えています.畝
クリエイトア 必要なすべての依存関係をインポートします.注意:すべてのカスタム関数の前にdotenvをインポートする方法を参照してください.
ミドルウェアを設置する.畝
JSONミドルウェアはJSONとして着信要求を解析するために使用されます.エクスプレスUrlencoded MiddlewareはURL符号化された要求を解析して、リクエスト本文にそれらを付けて、最終的にExpress Expressを使用して、パブリックファイルをブラウザに提供するために使用されます.
畝
連絡フォームルート.
あまり複雑でない.POSTリクエストを受け取るルート
次に、私たちはメーラー機能(私たちが2、3の中で得ます)に詳細を伝えています、そして、すべてがうまくいくならば、我々は成功とステータス200で応えます、そして、何かが間違っているならば、catchブロックはエラーと地位400に応じてキャッチします.
サーバーを起動します.
私たちは環境からポートを抽出しています、そして、1が利用できないならば、我々はそれに3000の値を割り当てます.次に、我々はアプリケーションを聞く方法を使用してサーバーを起動します.
クリエイトア すべての依存関係のインポート.Nodemailerと共に、我々は我々の電子メールとパスワードを
畝 メールトランスポートの作成.私たちはnodemailerサービスとしてGmailを使用している場合は、Gmailは簡単で、設定を迅速に任意のSMTPを使用することができます.
畝 電子メールに連絡先フォームの提出を送信する機能.使用
あなたがHTMLを送信することができますか何か簡単な場合は、テキストでそれを置き換える.そして最後に、我々は
畝 を作成する
畝 インデックスで.JSのインポートと呼び出しをコメントしない それをセットアップします.
クリエイトア プロジェクトのルートで
畝
オープン
畝
あなたは、我々が最初に加えたスクリプトを覚えています
また、TailWindCSS CLIを実行し、別のファイルでスタイルを出力するビルドスクリプトがあります.畝
それは、あなたがアプローチを使うものだけです.
次のコードを追加します
畝
スクリプトに次のコードを追加します.jsファイル.そして、何が実際に起こっているかを調べましょう.
畝
すべてのDOM要素はDOM APIを使用して呼び出され、変数に格納されています.畝 機能 機能 ドキュメントオブジェクトでは、イベントリスナーが「DomContentLoaded」と呼ばれるように追加され、HTMLファイルが読み込まれるとコールバック関数が発生します. HTMLファイルがすべてのコンテナを非表示にし、フォームを単独で表示し、最後にSubmitイベントをフォームに追加して そのように簡単に、あなただけの機能的な連絡先フォームを作った.それをテストし、あなたに連絡しようとしている人からのメールを受信します.畝
それがどのようにあなたのために働いたか、そして、何かがここに間違っているならば、私に知らせてください.
このチュートリアルでは、ノード、Express、NodeDailerとTailWindCSSを使用して連絡フォームを作成する方法を示します.フォームの応答を受け入れるためのカスタムルートを設定し、HTMLファイルをブラウザに提供し、TailWindCSSを使用してフォームとスタイルに機能を追加します.畝
必要条件
https://github.com/Kunal-Keshan/node-express-nodemailer-tailwindcss-contact-form
飛び込みましょう!畝
始める
node-express-nodemailer-tailwindcss-contact-form
😅 このプロジェクトの中で、端末またはVSコードを開きます.畝
npm i express nodemailer dotenv
npm i -D tailwindcss postcss autoprefixer nodemon concurrently
ExpressとNodemailerは、私たちの連絡先のフォームの機能を追加することができますコアパッケージは、dotenv私たちの電子メールのパスワードを保護することです.畝
TailWindCSS、PostCSS、およびAutoPrefixerは、我々のプロジェクトでTailwindクラスを使用できるようにする開発依存関係です.
畝
nodemonと同時に、新しい変更(nodemon)があるときにサーバーが再起動し、複数のスクリプトを同時に実行できるようにする開発依存関係です.
"start": "npm run build && node index.js",
"dev": "concurrently \"nodemon index.js\" \"npm run tailwind:watch\"",
"build": "npm run tailwind",
"tailwind": "npx tailwindcss -i tailwind.css -o public/style.css",
"tailwind:watch": "npx tailwindcss -i tailwind.css -o public/style.css --watch"
連絡先リクエスト
クリエイトア
index.js
あなたのプロジェクトの根源で、部分的にそれを見ましょう..env
ファイル./** index.js
* Contact Form Application
*/
// Dependencies
const express = require('express');
const path = require('path');
require('dotenv').config();
// const { sendContactEmail } = require('./mailer');
JSONミドルウェアはJSONとして着信要求を解析するために使用されます.エクスプレスUrlencoded MiddlewareはURL符号化された要求を解析して、リクエスト本文にそれらを付けて、最終的にExpress Expressを使用して、パブリックファイルをブラウザに提供するために使用されます.
// Initializing Express App
const app = express();
// Setting up middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, 'public')));
あまり複雑でない.POSTリクエストを受け取るルート
/api/contact
. 基本的な連絡先フォームは、名前、電子メール、あなたに連絡したい人のメッセージを収集するので、起動時に、我々は要求本文からそれらの詳細を破壊している.畝次に、私たちはメーラー機能(私たちが2、3の中で得ます)に詳細を伝えています、そして、すべてがうまくいくならば、我々は成功とステータス200で応えます、そして、何かが間違っているならば、catchブロックはエラーと地位400に応じてキャッチします.
// Application routes
/**
* @description Accept contact form data and send it to the server
* @api POST /api/contact
* @data {string} name, {string} email, {string} message
* @access Public
*/
app.post('/api/contact', async (req, res) => {
// Collecting required information from the Request Body
const { name, email, message } = req.body;
try {
// Sending the email
// await sendContactEmail({ to: email, name, message });
res
.status(200)
.json({
message: 'Email sent successfully',
data: { name, email, message },
success: true
});
} catch (error) {
console.log(error);
return res
.status(400)
.json({
message: 'Unable to process request',
data: {},
success: false,
})
}
})
私たちは環境からポートを抽出しています、そして、1が利用できないならば、我々はそれに3000の値を割り当てます.次に、我々はアプリケーションを聞く方法を使用してサーバーを起動します.
// Initialzing Server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
メーラー機能
クリエイトア
mail.js
ファイルをrootで調べ、その内容を一部探索しましょう.畝.env
ファイルも(いくつかの点で詳しく見るでしょう).畝
/** mail.js
* Node Mailer Setup
*/
// Dependencies
const nodemailer = require('nodemailer');
const email = process.env.MAIL_EMAIL;
const password = process.env.MAIL_PASSWORD;
畝
// Mail Transporter
const transport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: email,
pass: password,
},
from: 'Kunal Keshan <[email protected]>'
});
transport
sendMail
メソッドを設定し、オプションを設定すると、あなたのアカウントに電子メールを送信します.畝あなたがHTMLを送信することができますか何か簡単な場合は、テキストでそれを置き換える.そして最後に、我々は
sendMail
オプションを指定して返します.畝
/**
* @description Send email to the user
* @param {object} options
* @param {string} options.to
* @param {string} options.subject
* @param {string} options.message
*/
exports.sendContactEmail = ({ to, name, message }) => {
const mailOptionsToOwner = {
to: email,
subject: `Contact Form Submission from ${name} <${to}>`,
html: `
<h1>Contact Form Submission</h1>
<p>Name: ${name} <${to}></p>
<p>${message}</p>
`
}
const mailOptionsToUser = {
to,
subject: 'Thanks for contacting me!',
text: 'I will get back to you soon!'
}
return Promise.all([transport.sendMail(mailOptionsToOwner), transport.sendMail(mailOptionsToUser)]);
}
.env
ファイルを追加してメールやパスワードを追加します.nodemailerサービスとしてGmailアカウントを追加するには、2 FAを有効にする必要がありますし、アプリケーションのパスワードを作成する必要があります.この方法をチェックしてください.畝
# .env
# NODEMAILER CONFIG
MAIL_EMAIL=<[email protected]>
MAIL_PASSWORD=<app password here>
sendContactMail()
関数.畝前線
クリエイトア
public
プロジェクト内のディレクトリと - index.html
, style.css
, and script.js
. tailwind.css
ファイルを追加し、次の行を追加します.畝
@tailwind base;
@tailwind components;
@tailwind utilities;
コマンドラインで - npx tailwindcss init -p
. これは2つのファイルを作成しますtailwindcss.config.js
and postcss.config.js
プロジェクトで.畝オープン
tailwindcss.config.js
そして、あなたは、あなたがすでに存在している以下のオブジェクト構成を持つと気がつきます.畝
module.exports = {
content: [],
theme: {
extend: {},
},
plugins: [],
}
変更するcontent: []
そして、これに加えるcontent: ["./public/**/*.html"]
. これはTarwindCSSにHTMLファイルのクラスを見ていることを示しています.あなたは、我々が最初に加えたスクリプトを覚えています
package.json
? もう一つの時間です."start": "npm run build && node index.js",
"dev": "concurrently \"nodemon index.js\" \"npm run tailwind:watch\"",
"build": "npm run tailwind",
"tailwind": "npx tailwindcss -i tailwind.css -o public/style.css",
"tailwind:watch": "npx tailwindcss -i tailwind.css -o public/style.css --watch"
私たちは、私たちがプロジェクト(特にTailwind Configのために内容で言及したようにHTMLファイル)に我々がするどんな変更も見て、スタイルで使用されたクラスをスタイルに出力するのを見るために、Trewind CLIを使用します.同じパブリックディレクトリのCSS.ウォッチフラグは、変更を追跡するために使用されていることに注意してください.畝また、TailWindCSS CLIを実行し、別のファイルでスタイルを出力するビルドスクリプトがあります.畝
それは、あなたがアプローチを使うものだけです.
HTML - インデックス.HTML
次のコードを追加します
index.html
ファイル.<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Contact Form</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;1,300;1,400;1,500;1,600;1,700;1,800&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="/style.css" />
</head>
<body class="w-full h-screen flex flex-col gap-2 items-center justify-center bg-gradient-to-br from-green-400 to-blue-500 text-center">
<h1 class="text-2xl font-semibold">Contact</h1>
<form id="contact" class="w-full p-2 flex flex-col md:w-2/3 gap-2 lg:w-1/2" autocomplete="off">
<input type="text" name="name" id="name" placeholder="eg: John Smith" required class="py-1 px-2 border border-black rounded" />
<input type="email" name="email" id="email" placeholder="[email protected]" required class="py-1 px-2 border border-black rounded" />
<textarea name="message" id="message" placeholder="Hey! Let's get in touch, I want to..." required class="py-1 px-2 border border-black rounded resize-y" ></textarea>
<button type="submit" class="bg-blue-500 py-2 px-1 rounded text-md w-fit mx-auto font-semibold text-white hover:bg-opacity-100 bg-opacity-80" > Get in Touch! </button>
</form>
<div id="success" class="hidden text-md font-semibold"> You've successfully contacted me, I'll get back to you soon!</div>
<div id="error" class="hidden text-md font-semibold flex-col items-center justify-center">
<p>Oops! There's some error while sending me the contact details.</p>
<button class="bg-blue-500 py-2 px-1 rounded w-fit mx-auto text-white bg-opacity-80 hover:bg-opacity-100" onclick="javascript:window.location.reload();">Try again</button>
</div>
<div id="loading" class="hidden text-md font-semibold">Your Submission is being sent...</div>
<script src="/script.js"></script>
</body>
</html>
今、あなたがサーバーを起動するならば、NPM Run Devを使用して、あなたは以下のウェブサイトであなたのブラウザーで見ることができなければなりません.畝
機能性 - スクリプト。js
スクリプトに次のコードを追加します.jsファイル.そして、何が実際に起こっているかを調べましょう.
畝
/**
* Contact Form Functionality
*/
// Containers
const contactForm = document.getElementById('contact');
const loading = document.getElementById('loading');
const success = document.getElementById('success');
const errorEl = document.getElementById('error');
// Hide Container Function
const hideAllContainers = () => {
contactForm.style.display = 'none';
loading.style.display = 'none';
success.style.display = 'none';
errorEl.style.display = 'none';
}
// Contact Form Submit Handler
const handleContactFormSubmit = async (e) => {
e.preventDefault();
try {
contactForm.classList.add('animate-pulse');
loading.style.display = 'block';
const { name, email, message } = e.target;
const body = {
name: name.value,
email: email.value,
message: message.value,
}
const response = await fetch('/api/contact', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
if(response.status !== 200) throw response;
hideAllContainers();
contactForm.classList.remove('animate-pulse');
success.style.display = 'block';
} catch (error) {
hideAllContainers();
errorEl.style.display = 'flex';
}
}
document.addEventListener('DOMContentLoaded', () => {
hideAllContainers();
contactForm.style.display = 'flex';
contactForm.addEventListener("submit", handleContactFormSubmit);
});
hideAllContainers()
すべてのコンテナをスタイルプロパティにアクセスして非表示にするために使用します.畝handleContactFormSubmit()
はフォームの送信を処理するために使われる.すべてうまくいけば、成功divが表示され、何かが間違っている場合は、エラーdivは、フォームを再度入力しようとすると表示される表示されます.handleContactFormSubmit
コールバック関数として.それがどのようにあなたのために働いたか、そして、何かがここに間違っているならば、私に知らせてください.
Reference
この問題について(ノード、エクスプレス、nodemailer、およびTailWindCSSとの接触フォームを作成します.), 我々は、より多くの情報をここで見つけました https://dev.to/kunalkeshan/create-a-contact-form-with-node-express-nodemailer-and-tailwindcss-4j5cテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol