[英]Express.js Route orgainisation
When I set-up some Routes i normaly do it like this: 当我设置一些路线时,我通常这样做:
app.get('/x', function(req, res) {
res.sendFile(path.join(__dirname + '/public/.../index.html'));});
The Problem with this is if you have JS or CSS in the Route Folders you cant host them. 问题是如果路由文件夹中包含JS或CSS,则无法托管它们。
So often I just added 所以我经常加
app.get('/public/.../js/index.js', function(req, res) {res.sendFile (__dirname + '/public/.../js/index.js');});
app.get('/public/.../css/style.css', function(req, res) {res.sendFile (__dirname + '/public/.../css/style.css');});
just below the Route to make the JS and CSS accessible. 在Route下方,以使JS和CSS易于访问。
I already host library with express static 我已经托管了表达静态的图书馆
app.use('/lib', express.static('lib'));
But that is not Possible for JS and CSS in the Route folders (/public/.../js) 但这对于Route文件夹(/public/.../js)中的JS和CSS是不可能的
- Is There a better Way to organize my files that are in the route folders ?
有没有更好的方法来组织路径文件夹中的文件?
You might use virtual path, keeping your current directory structure, adding following route you can refer all your static files with /static prefix from under ./public subdirectory: 您可以使用虚拟路径,保持当前目录结构,添加以下路由,然后可以从./public子目录下引用所有带有/ static前缀的静态文件:
app.use('/static', express.static('public'))
Eg you would be able to refer http://your_server/static/public/.../js/index.js . 例如,您将可以参考http://your_server/static/public/.../js/index.js 。 Please be aware, that in such case all files under /public might be accessed via /static prefix, so you should not have server code or server configs there.
请注意,在这种情况下,/ public下的所有文件都可以通过/ static前缀访问,因此您不应在其中拥有服务器代码或服务器配置。
Ideally for clarity you should host and refer all your static files from one root folder with type subfolders (eg /static/js, /static/css): 理想情况下,为清晰起见,您应该从一个根文件夹中托管所有类型为子文件夹的静态文件,并引用这些子文件夹(例如/ static / js,/ static / css):
app.use('/static', express.static('static'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.