从同一目录提供静态内容和视图?

时间:2014-01-14 03:51:55

标签: node.js express ejs

是否可以从同一目录提供静态内容和视图? 我在下面找到了部分解决方案:

//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
}); 

这是完美的,除了没有渲染EJS的第一条路线'/'。所有其他路线(/ home,/ about等)将方便地为动态EJS和静态内容提供服务。无论如何都要欺骗第一个'/'以同样的方式工作?

1 个答案:

答案 0 :(得分:2)

对于Express 3.x,请尝试将路由器置于静态之前:

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

对于Express 4.x,路由器已被弃用,但概念与路由类似中间件一样,因此您应该能够在静态中间件之前调用它们。

相关问题