在express.js中使用路由服务静态文件
Serve static files using routes in express.js
我有一堆html文件,我想作为静态文件。但是,我需要路由中没有任何。html。
当路由为example.com/about它应该提供大约。html
我对提供静态文件所做的研究似乎表明,这不是完全可能的。是这样吗,还是我漏掉了什么?
你需要使用路由器
来提供你的静态文件app.get('/about', function(req, res) {
res.render('about.html');
});
在此之前,您应该为html呈现引擎设置一个中间件
或者如果你有很多静态文件,你可以使用中间件来为你做
https://www.npmjs.com/package/clean-urls您可以创建一小段中间件,它将处理您为其配置的任何预设名称。任何不在列表中的内容都将转到您的正常路由:
// create static file lookup table for the desired names
var staticFiles = ["about", "index", "home"].reduce(function(obj, item) {
obj["/" + item] = true;
return obj;
}, {});
app.use(function(req, res, next) {
// if the path is found in the lookup table, then
// add ".html" onto the end and get that file from the base directory
// of you could use any source directory for those files
if (staticFiles[req.path]) {
res.sendFile(path.join(__dirname, req.path + ".html"));
return;
}
next();
});
注意:这非常小心地只服务于特定的文件,所以没有人可以窥探你的文件系统与其他类型的url。
下面是一个示例,文件从基目录下名为"html"的子目录提供:
app.use(function(req, res, next) {
if (staticFiles[req.path]) {
res.sendFile(path.join(__dirname, "html", req.path + ".html"));
return;
}
next();
});
在节点v0.12+中,可以使用Set
对象作为静态路由列表,如下所示:
var staticFiles = new Set(["/about", "/index", "/home"]);
app.use(function(req, res, next) {
if (staticFiles.has(req.path)) {
res.sendFile(path.join(__dirname, "html", req.path + ".html"));
return;
}
next();
});
如果您有很多静态页面,理想的方法是将它们放在单个路由中,我们称之为static.js
。可以是这样的
module.exports = function () {
var router = require('express').Router();
var pages = {
'about-us': 'path/to/about-us',
'contact-us': 'path/to/contact-us'
};
router.get('/:page', function (req, res, next) {
if (! pages[req.params.page]) {
return next();
}
res.render(pages[req.params.page]);
});
return router;
};
将这条路线附加到应用程序,app.use(require('./static')());
和你很好去。
试试这个
app.use(express.static(path.join(__dirname, 'xyz')));
其中xyz是您试图使其作为静态可用的文件夹。文件夹名称相对于应用程序根目录
相关文章:
- 如何在从缓存加载路由后强制服务工作者从网络请求路由
- 如何使用路由提供程序在应用中调用模式服务
- 使用路由的未定义服务控制器
- 我可以在 angle js asp.net mvc 中调用控制器中的路由提供程序服务吗?
- 如何在刷新时将持久数据保存在角度路由服务中
- 使用角度 ui 路由器获取服务中的路由参数
- 角度 ui 路由器解析服务停止路由更改
- 为什么在重新加载路由时重新初始化 AngularJS 服务
- 从外部web服务获取图像并将其传递到另一个express js路由
- 如何在AgularJS服务中添加到$resource的路由
- 使用Angularjs服务的配置在.run()中生成路由
- 如何在angular.js中分别编写控制器、服务、路由和模块
- 分离角度路由、控制器和服务
- Node.js REST API服务中使用的基于资源的路由模块,或用于此类服务的其他有用模块
- 从Express服务的客户端React应用上的一致url路由
- 在谷歌地图API 3中清除方向服务的路由失败
- 为什么AngularJS的服务在从一个路由导航到另一个路由时没有定义?
- 检测Angular服务中的路由变化
- 如何将服务变量定义为当前路由
- 在express.js中使用路由服务静态文件