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

问题描述 投票:3回答:1

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

//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和静态内容提供服务。无论如何都要欺骗第一个'/'以同样的方式工作?

node.js express ejs
1个回答
2
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.