Click here to Skip to main content
15,885,918 members
Articles / Programming Languages / Javascript

Create a Simple Responsive website using Node, Express, Bootstrap and Jade - Part 3

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
16 Mar 2014CPOL4 min read 16.4K   6   4  
How to create a simple responsive website using Node, Express, Bootstrap and Jade - Part 3

If you are directly landing on this page, please read my previous article - Part 2.

In CodeProject, see Part2 [^] here.

You can download the source code here for reference.

Okay, now we are ready with the basic folder structure in hand, here is what I want you to do. Go to the routes folder, remove the existing files in the folder. Go to the Views folder, keep layout.jade, error.jade files and remove other files.

If you notice above .jade is the extension for jade template files. Express knows how to process those files into html files. Okay.., If you remember in our Sity Route website, we have two links Home and About. Home will take us to Home page and About will take us to About page, also there is a Learn More button which also currently I pointed to About page. So what is this paths mapping to Express is Routes (/Home,/About). We need to define these Routes in our application file, to tell express framework what needs to happen when it sees /Home or About as part of request.

Defining Route Handlers

Go to the routes folder and create two files, Home.js and About.js for two routes.

Home.js

JavaScript
/* GET home page. */
exports.home = function(req, res){
  res.render('home');
};

About.js

JavaScript
exports.about = function(req,res){
    res.render('about')
}

The above code is defining route handler modules for our website home and about. Meaning whenever we request home, it will execute the above home route, similarly about route too. Here res.render is express API function, which takes view name as parameter and will render the view, meaning it will convert the jade template to HTML string.

Create our Jade Views

Go to the views folder and create home.jade file and paste the following jade template content in it.

Home.jade

JavaScript
doctype html
html
  head
    title Sity Router Hub - A funny site
    meta(name='viewport', content='width=device-width, initial-scale=1.0')
    //
       Bootstrap CSS 
    link(href='stylesheets/bootstrap.css', rel='stylesheet', media='screen')
    link(href='mysite.css', rel='stylesheet', media='screen')
    script(type='text/javascript', src='javascripts/jquery.js')
    script(type='text/javascript', src='javascripts/bootstrap.min.js')
  body
    //
       Navigation Bar 
    .bodykinda
      .navbar.navbar-default
        .navbar-header
          button.navbar-toggle(type='button', data-toggle='collapse', 
               data-target='.navbar-responsive-collapse')
            span.icon-bar
            span.icon-bar
            span.icon-bar
          a.navbar-brand(href='#')
            | Sity Router Hub - A funny site- stories in this site not directly related 
              to any person on the earth or on other planets
        .navbar-collapse.collapse.navbar-responsive-collapse
          ul.nav.navbar-nav.navbar-right
            li.active
              a(href='#') Home
            li
              a(href='about') About
      //
         Navigation Bar 
    .jumbotron
      h1 City Router Hub
      p
        | Do you wanna get connected to internet securely on the go for no money..?, 
          meaning always connected, even if you don't have any device...?, 
          and wondering if this is ever possible. Well you are not alone, you are on the right spot.
      p
        a.btn.btn-primary.btn-lg(href='about') Learn More
    .col-lg-4
      .panel.panel-default
        .panel-heading
          h4  Join us. 
        .panel-body
          | Today if you make a choice,  you are going to get ever connected to 
            internet all the time through out your life, even if you go to villages, 
            subways, paths, metros, bus, Gym, anywhere it follows. Guys isn't that exciting?, 
            do you wanna know how, take a minute and click on above Learn More link.
    .col-lg-4
      .panel.panel-default
        .panel-heading
          h4 Always Connected.
        .panel-body
          | You are absolutely free of money, credit cards, debit cards, paypal, 
            coupon cards what so ever. This service is amazingly free and free only for you, 
            if you register today. Do you know how many people out there paying lot of money 
            but not getting exciting service, they always had problems with speed, connectivity.
    .col-lg-4
      .panel.panel-default
        .panel-heading
          h4 Who are we? 
        .panel-body
          | We are top 10 listed Unfortune 500 companies, always wanted to give people 
            service with no money. There are similar services who can offer like free wifis, 
            metro wifi. Well their reach is limited. We are unlimited. Anywhere you go, 
            our services will follow. We are on different world and different platforms, 
            nobody can match us.

and create about.jade file and paste the following content in it.

about.jade

JavaScript
doctype html
html
  head
    title Sity Router Hub - A funny site
    meta(name='viewport', content='width=device-width, initial-scale=1.0')
    //
       Bootstrap CSS 
    link(href='stylesheets/bootstrap.css', rel='stylesheet', media='screen')
    link(href='mysite.css', rel='stylesheet', media='screen')
    script(type='text/javascript', src='javascripts/jquery.js')
    script(type='text/javascript', src='javascripts/bootstrap.min.js')
  body
    //
       Navigation Bar 
    .bodykinda
      .navbar.navbar-default
        .navbar-header
          button.navbar-toggle(type='button', 
          data-toggle='collapse', data-target='.navbar-responsive-collapse')
            span.icon-bar
            span.icon-bar
            span.icon-bar
          a.navbar-brand(href='#')
            | Sity Router Hub - A funny site- stories in this site 
            not directly related to any person on the earth or on other planets
        .navbar-collapse.collapse.navbar-responsive-collapse
          ul.nav.navbar-nav.navbar-right
            li.active
              a(href='#') Home
            li
              a(href='about') About
      //
         Navigation Bar 
    .jumbotron
      h1 City Router Hub
      p
        | Do you wanna get connected to internet securely on the go for no money..?, 
        meaning always connected, even if you don't have any device...?, 
        and wondering if this is ever possible. Well you are not alone, you are on the right spot.
      p
        a.btn.btn-primary.btn-lg(href='about') Learn More
    .col-lg-4
      .panel.panel-default
        .panel-heading
          h4  Join us. 
        .panel-body
          | Today if you make a choice,  you are going to get ever connected to 
          internet all the time through out your life, even if you go to villages, 
          subways, paths, metros, bus, Gym, anywhere it follows. Guys isn't that exciting?,
          do you wanna know how, take a minute and click on above Learn More link.
    .col-lg-4
      .panel.panel-default
        .panel-heading
          h4 Always Connected.
        .panel-body
          | You are absolutely free of money, credit cards, debit cards, paypal, 
          coupon cards what so ever. This service is amazingly free and free only for you, 
          if you register today. Do you know how many people out there paying lot of money 
          but not getting exciting service, they always had problems with speed, connectivity.
    .col-lg-4
      .panel.panel-default
        .panel-heading
          h4 Who are we? 
        .panel-body
          | We are top 10 listed Unfortune 500 companies, always wanted to give people 
          service with no money. There are similar services who can offer like free wifis, 
          metro wifi. Well their reach is limited. We are unlimited. Anywhere you go, 
          our services will follow. We are on different world and different platforms, 
          nobody can match us.

Don’t worry about the above jade code if it really bothers you too much at this point, because this is really not tough to do if you know jade templating, if you want, you can go with some simple stuff too.

Now Let Us Come to app.js Application File

app.js file is basically the heart of the application, here we define our websites' middleware functionality, such as cookies, body parser, sessions, authentication, authorization, defining routes, csrf stuff, etc. There are many out of the box middleware framework functions shipped with express framework. Please visit the express site if you are interested.

Here, basically you need to load the home, about route handlers we defined above into the application, in node, you will load the module using require. Take a look below.

JavaScript
var home = require('./routes/home');
var about = require('./routes/about');

Now we loaded route handlers, we haven’t yet defined routes, let us do that. We use app.get express API for that.

JavaScript
app.get('/', home.home);
app.get('/home', home.home);
app.get('/about', about.about);

In the above code, we are mapping a default site request ‘/’ to our home route handler, specific ‘/home’ to home, ‘/about’ to about route handler. Okay, those route handlers are going to render jade views defined in Views folder, so here is how we tell node express to use jade templates.

JavaScript
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

if you observe the above environmental value ‘view engine’ is set to ‘jade’, we can set this to other node compatible view engines too.

You can define error handler in your middleware to like below, if any 404 request is coming to your server, then how do you display default error message, here is how.

JavaScript
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.render('error', {
        message: err.message,
        error: {}
    });
});

This will be created with default scaffold, but let me explain what it does. We are adding a middleware function to express framework, telling it how to process any request that doesn’t match any of the defined routes, ideally this would be at the end of your declaration of routes. We created 404 error in one of the middleware functions and we pass it on to error handler. Here, error handler is defined for both production and development environments can be switched just by changing the node environment variable ‘env’. So we are done with all the modifications. Find out how we can host this node app on public site here.

You can run the app using command line node app.js and access the app at 3000 port.

If you would like to host real time on Cloud, learn how to it from Hosting in Cloud.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
I have around 9 years of experience in Microsoft technologies, .Net 2.0,3.5, Asp.net MVC developed small to medium scale products using Silverlight 2.0, Asp.net Ajax technologie and Javascript frameworks.

Comments and Discussions

 
-- There are no messages in this forum --