表示多个静态路由正则expression式parsing
我试图用express来从两个目录提供静态文件。
我从两个目录提供服务的原因是由于在目录#2中具有匹配的目录名称的目录#1中服务的文件之间的冲突
在目录#1中,它将只包含文件:
/path/to/dir1/foo (where 'foo' is a file)
在目录#2中,它将包含包含文件的子目录:
/path/to/dir2/foo/bar (where 'foo' is a dir && 'bar' is a file)
我的目标是能够执行以下命令:
wget "http://myserver:9006/foo" wget "http://myserver:9006/foo/bar"
下面的代码将完成所有的事情,直到我目录#2:
"use strict"; const express = require('express'); const app = express(); app.use('/', express.static('/path/to/dir1/')) const server = app.listen(9006, () => { let host = server.address().address; let port = server.address().port; console.log(`Example app listening at http://${host}:${port}`); });
我试图用正则expression式添加第二个静态路由,看是否在路由中有一个'/',这样我就可以将它指向目录#2。 我正在思考这方面的一些事情,但还没有取得任何成就:
app.use('/[^/]*([/].*)?', express.static('/path/to/dir2/'));
要么
app.use('/.*/.*', express.static('/path/to/dir2/'));
我将不胜感激任何帮助。
提前致谢!
根据文档 ,您可以多次调用express.static
,它将按照您指定的目录顺序search文件。
文件夹结构:
/ static/ s1/ foo # Contents: s1/foo the file s2/ foo/ bar # Contents: s2/foo/bar the file.
该应用程序是您的确切代码除了两个静态行:
const express = require('express') const app = express() app.use('/', express.static('static/s1')) app.use('/', express.static('static/s2')) const server = app.listen(9006, () => { let host = server.address().address let port = server.address().port console.log(`Example app listening at http://${host}:${port}`) })
页面按预期工作
$ curl localhost:9006/foo s1/foo the file $ curl localhost:9006/foo/bar s2/foo/bar the file.