Serve static content and views from the same directory?

Is it possible to use static content and views from the same directory? I found a partial solution below:

//Enable Express static content serving:  
app.use(express.static(__dirname + '/html')); //Static path is folder called html

//Also enable EJS template engine: 
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/html'); //Set views path to that same html folder
app.set('view engine', 'html'); //Instead of .ejs, look for .html extension

//Start server
app.listen(8000);

//Express routes: 
app.get('/', function(req,res) {
    res.render('index', { message: 'hello world'});   
    //this only serves static index.html :(
}); 

app.get('/home', function(req,res) {
    res.render('index', { message: 'hello world'}); //<-- this serves EJS
    //whoo-hoo! serves index.html with rendered EJS 'hello world' message
}); 

This works fine except for the first '/' route, which does not display EJS. All other routes (/ home, / about, etc.) will conveniently serve dynamic EJS along with static content. Should I even deceive that the first "/" works the same way?

+3
source share
1 answer

For Express 3.x, try putting the router in front of static:

 app.use(app.router);
 app.use(express.static(path.join(__dirname, 'html')));

Express 4.x , , , , .

+2

All Articles