Contact Us

How to create a simple contact form with Node.js?

Let’s start by creating an empty folder and initializing our package.json with npm init . We will also include express to set up our application, express-validator to validate the form submission, and mustache (mustache-express) to render the form.

npm init -y npm i --save express express-validator mustache-express

The basics.

With our packages ready, let’s go on and create our index.js . We will start by including our packages and creating the express app with the express router:

const path = require('path'); const < body, validationResult >= require('express-validator'); const express = require('express'); const mustacheExpress = require('mustache-express'); const port = 8000; const app = express(); const router = express.Router(); // process POST forms app.use(express.urlencoded(< extended: true >));

For this example, our router will be as simple as one controller for GET and one for POST of the home route (we will work on the POST controller later in the course):

With this in place, we need to configure what and where is going to render our home template. We need to register our mustache engine, and configure it to look for templates in our views folder:

// html rendering app.engine('mustache', mustacheExpress()); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'mustache');

We are good with HTML rendering, and we can now continue on with the styles.

Setting up the public folder, and preparing Tailwind CSS.

Let’s add another app.use to mark the folder as public, and to serve all the resources directly from that folder.

// public files app.use(express.static(path.join(__dirname, 'public')));

After the static folder is set, let’s go back to the command line and produce a full version of Tailwind CSS. This is the least recommended way (as it produces around 4MB of CSS, out of which you might use like 1-2KB), but we are mostly doing this to see how to handle the forms in Node.js, so let’s continue:

npx tailwindcss -o public/css/tailwind.css

Now that our public folder is setup, and we have a base Tailwind CSS, all we need to do is use our router and run the server:

// controllers app.use(router); // run! app.listen(port, () => < console.log(`Server started at port $`) >);

Tip: while working on templates, it might be useful to run nodemon to watch your file changes and reload the server automatically, so include mustache into the list of extensions as well, such as:

Handling the form and validating submission.

With all the setup done, we can start writing the POST controller. It should have a few key elements: validator middleware, displaying the errors, rendering previously input value, and displaying the success message. Let’s start with very very basic validation, we’ll check that both fields are at least 2 characters long:

router.post('/', body('name').isLength(< min: 2 >).withMessage('Please input your name'), body('message').isLength(< min: 2 >).withMessage('Please input your message'), (req, res, next) => < const errors = validationResult(req); . 

Here we use the body middleware from express-validator, and the validatorResult to collect all the errors into an array. If there are any errors, we render the same form again, but add the errors array and the values that we just sent:

Now that we validated our fields, we can use our fields (send them via e-mail, save to database etc.). After we processed our fields are in req.body , we can render the thankyou template:

// req.body.name // req.body.message // render thank you res.render('thankyou');

The form layout

I won’t describe the visual aspects of the template, will only note that there is an #errors loop to output the validation errors, and there’s a render of field values in case there was a validation error and we don’t want to lose our input:

        

Contact Us

>
>
>

>" />

The thank you page can just be a very basic static html:

        

Thank you!

Your message has been sent

And, here is the full code of the app:

const path = require('path'); const < body, validationResult >= require('express-validator'); const express = require('express'); const mustacheExpress = require('mustache-express'); const port = 8000; const app = express(); const router = express.Router(); // process POST forms app.use(express.urlencoded(< extended: true >)); // html rendering app.engine('mustache', mustacheExpress()); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'mustache'); // public files app.use(express.static(path.join(__dirname, 'public'))); // controllers router.get('/', (req, res, next) => < res.render('home'); >); router.post('/', body('name').isLength(< min: 2 >).withMessage('Please input your name'), body('message').isLength(< min: 2 >).withMessage('Please input your message'), (req, res, next) => < const errors = validationResult(req); if (!errors.isEmpty()) < return res.status(400).render('home', < errors: errors.array(), name: req.body.name, message: req.body.message >); > // do something with the fields // req.body.name // req.body.message // render thank you res.render('thankyou'); > ); app.use(router); // run! app.listen(port, () => < console.log(`Server started at port $`) >);

Источник

# Creating a contact form

We have our Contact Service email service and Contact Form email template from the previous steps. Let's create a simple HTML form and send its content by email.

DOCTYPE html> html> head> title>Contact Formtitle> script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@emailjs/browser@3/dist/email.min.js"> script> script type="text/javascript"> (function()  // https://dashboard.emailjs.com/admin/account emailjs.init('YOUR_PUBLIC_KEY'); >)(); script> script type="text/javascript"> window.onload = function()  document.getElementById('contact-form').addEventListener('submit', function(event)  event.preventDefault(); // generate a five digit number for the contact_number variable this.contact_number.value = Math.random() * 100000 | 0; // these IDs from the previous steps emailjs.sendForm('contact_service', 'contact_form', this) .then(function()  console.log('SUCCESS!'); >, function(error)  console.log('FAILED. ', error); >); >); > script> head> body> form id="contact-form"> input type="hidden" name="contact_number"> label>Namelabel> input type="text" name="user_name"> label>Emaillabel> input type="email" name="user_email"> label>Messagelabel> textarea name="message">textarea> input type="submit" value="Send"> form> body> html> 

You can obtain your public key from the Account

(opens new window) page in the EmailJS dashboard. After filling the fields and sending the request we should find the new email in our personal inbox. If you can't find it take a look at the spam folder.

# So what did we do?

First, we load our EmailJS SDK

script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@emailjs/browser@3/dist/email.min.js"> script> 

Second, we initialize the SDK with our public key

emailjs.init('YOUR_PUBLIC_KEY'); 

Third, we submit our contact form and send it through EmailJS, using our Contact Service and Contact Form:

emailjs.sendForm('contact_service', 'contact_form', this) 

# That’s it!

You now have a contact form that sends all submissions to your inbox via your own Gmail account.

Источник

Читайте также:  Инкапсуляция си шарп пример
Оцените статью