【问题标题】:Serve static content and views from same directory?从同一目录提供静态内容和视图?
【发布时间】:2014-01-14 03:51:55
【问题描述】:

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

//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】:

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

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

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

    【讨论】:

    • app.router 似乎已被弃用,并且不再有效。
    • @cgmb - 谢谢 - 我在帖子中做了一个注释。该过程应该与我假设的相同,因为它都是先到先使用中间件。
    猜你喜欢
    • 2017-10-06
    • 2012-12-14
    • 2013-12-03
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    相关资源
    最近更新 更多