Serve static content and views from same directory?

冷暖自知 提交于 2019-12-23 19:12:26

问题


Is it possible to serve 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 is working perfectly, except for the first route '/' which does not render EJS. All other routes (/home, /about, etc) will conveniently serve the dynamic EJS along with static content. Is there anyway to trick that first '/' to work in the same way?


回答1:


For Express 3.x try putting router before static:

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

For Express 4.x the router has been deprecated but the concept is the same as routes are like middleware so you should be able to call them before the static middleware.



来源:https://stackoverflow.com/questions/21105801/serve-static-content-and-views-from-same-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!