I\'m using this to have Node.js/Express setup as a rudimentary web server - it just serves a set of static pages without any other processing. I\'d like it to always serve /
I've added my own variation with some extra "meat" on it to demonstrate how you can even include routing. I put all the following code in a file called "routes.js":
var express = require('express'),
painting = require('./controllers').Painting,
gallery = require('./controllers').Gallery;
module.exports.initialize = function(appSvr, router) {
router.get('/paintings', painting.list);
router.get('/galleries', gallery.list);
appSvr.use('/', router);
appSvr.use('/', express.static(__dirname + '/../public', { index: 'index.html' }));
};
I then call this file in my "configure.js" file that will be required in my "server.js" file:
var routes = require('./routes'),
express = require('express'),
bodyParser = require('body-parser');
module.exports = function(appSvr) {
appSvr.use(bodyParser.urlencoded());
appSvr.use(bodyParser.json());
routes.initialize(appSvr, new express.Router());
return appSvr;
};
I haven't seen how best to handle routing, but this code seems to work for me.
Would love some feedback!
It's weird that no one mentioned redirection.
app.get('/', function(req, res){
res.redirect('/default.html');
});
This -of course- assumes that you have your 'default.html' at the public path. You can set your public path by using:
app.use(express.static(relative_path_to_project_root));
I looked briefly for the best practices for serving a public folder and specifying the default page to serve. After reviewing the 'Express middleware' documentation, my solution looks like the following,
var express = require('express');
var app = express();
var options = {
index: "coming-soon.html"
};
app.use('/', express.static('app', options));
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log('my app is listening at http://%s:%s', host, port);
});
You could do something like this. Assuming its an html file that is relative to the .js file:
app.get('/', function(req, res){
res.sendfile('default.html', { root: __dirname + "/relative_path_of_file" } );
});