user2582622 user2582622 - 2 months ago 8x
HTML Question

Web Application with Forms in NodeJS

So I'm developing a website where a section of the website will be provide means to send comments to us on how to improve it. This section will ask for the user's name, email address, and have a text box. I want the user to be able to click send and have that message as well as their name and email address to be delivered to a designated email address.

That way the admins of the website can look over the website and attempt to make the content more relative to what the users demand. I'm using NodeJS but what I'm confused about is how to actually implement that. I've never done anything like with communication to the backend so I'm very confused on how to start.

Initially, I thought I could make a php script with HTML to do that function, but knowing that NodeJS is a server side scripting language, I know there should be some way to incorporate that in my web application. I googled but I'm a beginner with NodeJS so I was not fully ably to comprehend. If someone could assist me with this problem, it would be highly appreciated.

Thank you so much!


When you have to create a page with a webform, you have to create GET and POST request.

On your GET request you have to display a valid HTML page. To do that you have to choose a template engines, I use handlebar but you are free to choose your own (jade, ejs, ...).


var express = require('express');
var app = express();
var expressHbs = require('express3-handlebars');

app.engine('hbs', expressHbs({extname:'hbs'}));
app.set('view engine', 'hbs');
app.get('/pages/contact', function(req, res){

// this form send a post request to /pages/contact
<form action='/pages/contact' method='post'>
  <input type='text' name='username' id='username'/>  
  <input type='text' name='mail' id='mail'/>
  <input type='text' name='message' id='message'/>

If you want to add more security controls on your form take a look at helmet.

On your POST request, you have to do an action, here it's to save the form (or send information via email).

  1. You need to validate your input data
  2. You need to sanitize your input data
  3. You need to proccess your data to mongodb, nodemailer or mandrill

Take a look at express-validator.


var expressValidator = require('express-validator');'/pages/contact', function(req, res) {
 // checkBody only checks req.body

 req.checkBody('username', 'Invalid username').notEmpty().isAlpha();
 req.checkBody('mail', 'Invalid email').isEmail();
 req.checkBody('message', 'Invalid message').notEmpty();

 var errors = req.validationErrors();
 if (errors) {
  res.send('There have been validation errors: ' + util.inspect(errors),  400);
 // Proccess your data here via mandrill, nodemailer or mongoose.

Another popular solution is to use caolan/forms.

PS: Send an email is not a simple task, take a look at mailchimp, mandrill, mailjet, mailgun ...