Using Express with Mustache

323 views
Skip to first unread message

Neeraj Jadhav

unread,
Mar 3, 2016, 12:54:06 PM3/3/16
to Express
I am writing a Node.js-Express.js web application and have chosen Mustache as my desired template framework. I am new to mustache but I have written a sample node js app a year ago using Hogan. I was trying to replicate what I had in my old app but I guess Express 4.x has changed a couple of things, especially when it comes to the router. This is what I have so far:

app.js

var express = require('express');                               
var router = express.Router();                                  
var bodyParser = require('body-parser');                        
var methodOverride = require('method-override');                
var favicon = require('serve-favicon');                         
var http = require('http');
var path = require('path'); 
var mysql = require('mysql');
var mustacheExpress = require('mustache-express');

var app = express();                                            

app.engine('html', mustacheExpress());                          

app.set('port', process.env.PORT || 8000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');

app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(express.static(path.join(__dirname, 'public')));        
app.use(bodyParser.urlencoded({'extended':'true'}));           
app.use(bodyParser.json());                                     
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); 
app.use(methodOverride());

//home page route
router.get('/', function(req, res){
  res.render('index', {
    title:'my index page',
    projects: 'Projects inserted from node server',
    dbrows: 'Database rows'
  });
});

//create server and listen to the port
http.createServer(app).listen(app.get('port'), function(){
    console.log('Express server listening on port ' + app.get('port'));
});

module.exports = app;


This code works perfectly. The index.html is present in the views folder (along with other .html files). My question is, I am rendering the index.html from app.js and sending it the values. What if I need to do some other operations (like calling a database) before rendering the index (or any other page for that matter)?

Do I create an index.js file in routes folder and move my get and post there? If yes then how will it look? I created an index.js in the routes folder and gave it the following code, but it is not working. Any idea on what I am doing wrong?

index.js


var express = require('express');
var router = express.Router();
var mysql = require('mysql');

var connection = mysql.createConnection({
  host     : 'databse.amazon.aws.com',
  user     : 'username',
  password : 'password',
  port: '3306',
  database : 'my_test_db'
});

//home page route
router.get('/', function(req, res){

    connection.connect();
    //reading from database
    connection.query('SELECT * FROM Projects', function(err, rows, fields) {
      if (err) {
        console.log('error connecting to db');
        return;
      }

        res.render('index', {
            title:'my index page',
            projects: 'Projects in Brackets inserted from node server)',
            dbrows: JSON.stringify(rows)
        });
    });

    connection.end();
});
Reply all
Reply to author
Forward
0 new messages