[英]Nodejs and express static view routing
My question is very similar to this stackoverflow question. 我的问题与这个 stackoverflow问题非常相似。
I have my directory structure as: 我的目录结构为:
|-static
|---css
|---img
|---js
|-views
|---login.ejs
|---pure.html
|---dash
|-----dashboard.ejs
|-----alsopure.html
My configuration: 我的配置:
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/static'));
I have also defined the routes as: 我也将路线定义为:
app.get('/login', function(req,res){
//some locals
res.render('login.ejs', locals);
});
app.get('/dash', function(req,res){
locals.date = new Date().toLocaleDateString();
res.render('dash/dashboard.ejs', locals);
});
In the views folder, I keep both my pure static html and my dynamic ejs
files. 在views文件夹中,我同时保留了纯静态html和动态
ejs
文件。
Now, how do I serve the static html from the views directory? 现在,如何从views目录中提供静态html? Since if I would add the /views folder to serve as a static the user would be able to see my ejs files as well, if they hit the correct url.
因为如果我将/ views文件夹添加为静态文件夹,那么用户只要按正确的URL,就可以看到我的ejs文件。
Since there are multiple html files, I would not like to add a new route for every new page. 由于存在多个html文件,因此我不想为每个新页面添加新的路由。
Also, is there any way for me to indicate to my view engine that is a static html and there's no need to 'process' this page? 另外,有什么方法可以向我的视图引擎表明它是静态html,而无需“处理”此页面吗?
Thanks! 谢谢!
So, You can use nodejs
fs
and then routes be like : 因此,您可以使用
nodejs
fs
,然后路由如下所示:
app.get(/.*/, function(req, res, next) {
var path = __dirname + '/views/' + req.path + '.html';
if(fs.existsSync(path)) {
// Consolidate function to load html with path
}
else {
next();
}
}
Or you can just use it as middleware : 或者,您也可以将其用作中间件:
app.use(function(req, res, next) {
var path = __dirname + '/views/' + req.path + '.html';
if(fs.existsSync(path)) {
// Consolidate function to load html with path
}
else {
next();
}
}
but i think it will become a bloat for your program :). 但我认为这将成为您程序的膨胀:)。 because for every response it will search for the html file.
因为对于每个响应,它将搜索html文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.