Home > mongodb, nodeJS > Handling static content with node.js and express

Handling static content with node.js and express

nodejs

While working with the integration of jquery data table with nodejs via express framework, encountered some problems of loading css and js files to the web application. Here is the app.js code i have used before fixing the issue.

</p>
var express = require('express')
, app = express() // Web framework to handle routing requests
, cons = require('consolidate') // Templating library adapter for Express
, MongoClient = require('mongodb').MongoClient // Driver for connecting to MongoDB
, routes = require('./routes'); // Routes for our application

MongoClient.connect('mongodb://localhost:27017/school', function(err, db) {
"use strict";
if(err) throw err;

// Register our templating engine
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');

// Express middleware to populate 'req.cookies' so we can access cookies
app.use(express.cookieParser());

// Express middleware to populate 'req.body' so we can access POST variables
app.use(express.bodyParser());

// Application routes
routes(app, db);

app.listen(3000);
console.log('Express server listening on port 3000');
});

Here is the part html file i have used.


<title>School List</title>
 <style type="text/css" title="currentStyle">
 @import "media/css/demo_page.css";
 @import "media/css/demo_table.css";
 </style>
 <script type="text/javascript" language="javascript" src="media/js/jquery.js"></script>
 <script type="text/javascript" language="javascript" src="media/js/jquery.dataTables.js"></script>
 <script type="text/javascript" charset="utf-8">
 $(document).ready(function() {
 $('#example').dataTable();
 } );
 </script>

The above node.js code will create and run the server at port 3000. Since we are using express as MVC framework we need the tell the server about the location of static files as follows.


app.use(express.static(__dirname + '/views'));

This code segment should be put under the app.set(); code line. And here is the folder structure.

Project

app.js

/views

/media

/index.html

Advertisements
Categories: mongodb, nodeJS
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: