title: Sending error message to a html page after validating form fields using express js server
body: <p>I am new to node js. I want to create a login page and with two fields ie username and password. I am using mongodb as database. After validating the two fields at server I need to redirect it to home page. In case of any validation errors I want to display appropriate error message in the same html page(ie login.html) without loosing the entered fields. I want to achieve it using plain html without any view engines like ejs, jade etc. Currently in case of any invalid parameters only error message is getting displayed without the html page content. </p>
  
  <p>May I know how to achieve it.
  Here is my code</p>
  
  <p><strong>app.js</strong></p>
  
  <pre><code>    var express = require('express');
  
      var app = express();
  
      var path = require('path');
  
      var favicon = require('serve-favicon');
  
      var logger = require('morgan');
  
      var cookieParser = require('cookie-parser');
  
      var bodyParser = require('body-parser');
  
      var http = require('http');
  
  
      // New Code
      var mongo = require('mongodb');
  
      var monk = require('monk');
  
      var db = monk('localhost:27017/exampleDb');
  
  
      // view engine setup
      app.use(logger('dev'));
  
      app.use(bodyParser.json());
  
      app.use(bodyParser.urlencoded({ extended: false }));
  
      app.use(cookieParser());
  
      app.use(express.static((__dirname, 'public')));
  
      app.use(require('./routes/reg'));
  
      // Make our db accessible to our router
      app.use(function(req,res,next){
                                        req.db = db;
                                        next();
                                    });
  
      var server = app.listen(8081, function () {
  
        var host = server.address().address
  
        var port = server.address().port
  
        console.log("Example app listening at http://%s:%s", host, port)
  
      });
  
      module.exports = app;
  
  
   - 
  </code></pre>
  
  <p><strong>reg.js(inside routes folder)</strong></p>
  
  <pre><code>    var express = require('express');
  
      var app = express();
  
      //var fs = require("fs");
  
      var bodyParser = require('body-parser');
  
      var multer  = require('multer');
  
      var router = express.Router();
  
      app.use(express.static('public'));
  
      app.use(bodyParser.urlencoded({ extended: false }));
  
      //require/import the mongodb native drivers.
  
      var mongodb = require('mongodb');
  
      // "MongoClient" interface in order to connect to a mongodb server.
  
      var MongoClient = mongodb.MongoClient;
  
      // Connection URL. This is where your mongodb server is running.
  
      var url = 'mongodb://localhost:27017/exampleDb';
  
      var dbglobal = '';
  
      // Use connect method to connect to the Server
  
      MongoClient.connect(url, function (err, db) 
      {
            dbglobal = db;
  
            if (err) 
  
            {
  
              console.log('Unable to connect to the mongoDB server. Error:', err);
  
      } 
            else 
  
            {
                  //Connection Success
  
                  console.log('Connection established to', url);
  
                  // Database Operations
  
                  var collection = db.collection('users');
            } 
      });
  
      function authenticateUser(username, password, callback){
  
        var coll = dbglobal.collection('users');
  
        coll.findOne({user_name: username, password:password}, function(err, user){
  
          console.log("Authenticating user:" +username);
  
          callback(err, user);
  
        });
      }
  
      //api for handling user Login
      router.post('/login', function (req, res) {
  
                          console.log("User login");
  
                          var db = dbglobal;
  
                          var uname = req.body.username;
  
                          var password = req.body.password;
  
                          if(uname){
                                      if(password){
                                                      //var collection = db.collection('users');
                                                      authenticateUser(uname, password, function(err, user){
                                                          if (user) {
                                                                        // This way subsequent requests will know the user is logged in.
                                                                        //req.session.username = user.username;
                                                                        console.log(user);//req.session.username  
                                                                        res.send('Login Success');//need to display it in home page
                                                                      } else {
                                                                                res.send('Bad credentials'); // need to display it in same login page with enterer fields
                                                                      }
                                                      });
                                      }
                                      res.send("invalid password");
                          }
                          else{
                              res.send("invalid user name");
                          }
      });
  
      module.exports = router;
  </code></pre>
  
  <p><strong>login.html page</strong></p>
  
  <pre><code>&lt;html&gt;
  
  &lt;head&gt;
  
  &lt;title&gt;
           Login
  &lt;/title&gt;
      &lt;script type ="text/javascript" src="../scripts/jquery-1.11.3.js"&gt;&lt;/script&gt;
  
      &lt;link rel="stylesheet" href="../styles/bootstrap.min.css"&gt;
  
      &lt;link rel="stylesheet" href="../styles/bootstrap-theme.min.css"&gt;
  
      &lt;script type ="text/javascript" src="../scripts/bootstrap.min.js"&gt;&lt;/script&gt;
  
      &lt;script type ="text/javascript" src="../scripts/loginHandler.js"&gt;&lt;/script&gt;
  
  &lt;/head&gt;
  
  &lt;body onload="setFirstFocus();"&gt;
  
          &lt;form action="http://127.0.0.1:8081/login" method="POST" name="login"&gt;
  
          &lt;div style=" width:20%;border-radius:2%;margin-top:5%;margin-left:5%;"&gt;
  
                      &lt;div class="form-group" style="width:80%;height:10%;margin-left:2%;"&gt;
  
  &lt;label for="username"&gt;Username&lt;/label&gt;
  
  &lt;input type="text" class="form-control" id="username" name="username" onblur="return(validateUserName());"&gt;
  
  &lt;span id="UserNameError"&gt;&lt;/span&gt;
  
                      &lt;/div&gt;
  
                      &lt;div class="form-group" style="width:80%;height:10%;margin-top:.5%;margin-left:2%;"&gt;
  
                      &lt;label for="password"&gt;Password &lt;/label&gt;
  
                      &lt;input type="password" class="form-control" id="password" name="password" onblur="return(validatePassword());"&gt;
  
                      &lt;span id="pwdError"&gt;&lt;/span&gt;
  
                      &lt;/div&gt;
  
                      &lt;div id="lower" class="form-group"&gt;
  
                          &lt;input type="submit" value="Login" class="btn btn-info pull-center" style="margin-left:25%;"&gt;
  
                      &lt;/div&gt;&lt;!--/ lower--&gt;
                  &lt;/div&gt;
          &lt;/form&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>