tl;dr;
我错误地认为 url /test/whatever/path 代表一个抽象的虚拟操作(类似于 ASP.NET MVC 路由),而不是服务器上的具体物理文件。 restify 不是这样。
restify 的工作原理是,对于静态资源,无论您在 url 上键入什么内容,它都必须存在于服务器的磁盘上,从“目录”中指定的路径开始。
所以当我请求 localhost:8080/test 时,我实际上是在磁盘上寻找资源 /myPublic/test/testPage.html;如果我输入 localhost:8080/test/otherPage.html,我实际上是在磁盘上寻找资源 /myPublic/test/otherPage.html。
详情:
第一条路线
server.get('.*', restify.serveStatic({
'directory': __dirname + '/myPublic',
'default': 'testPage.html'
}));
RegEx '.*' 表示匹配任何东西!所以在浏览器中我可以输入
localhost:8080/, localhost:8080/testPage.html, localhost:8080/otherPage.html, localhost:8080/whatever /testPage.html、localhost:8080/akira/fubuki/ 等,GET 请求最终将被路由到上述处理程序,并提供路径 /myPublic/ testPage.html, /myPublic/otherPage.html, /myPublic/whatever/testpage.html, /myPublic/akira/fubuki/testpage.html 等存在磁盘,请求将被处理。
第二条路线
server.get('/test', restify.serveStatic({
'directory': __dirname + '/myPublic',
'default': 'testPage.html'
}));
此处理程序将匹配获取请求 localhost:8080/test,并将提供磁盘上的默认页面 public/test/testPage.html。。 p>
为了让处理程序更灵活,我可以使用正则表达式
server.get(/\/test.*\/.*/, restify.serveStatic({
'directory': __dirname + '/myPublic',
'default': 'testPage.html'
}));
此 RegEx 表示匹配 '/test' 后跟任何字符 (.) 0 次或多次 (*),然后是斜杠 (/),然后是任何字符 0 次或多次。示例可以是 localhost:8080/test/、localhost:8080/testis/、localhost:8080/testicles/、localhost: 8080/test/otherPage.html,localhost:8080/testicles/otherPage.html,并提供路径+相应文件存在于磁盘上,例如/public/test/testPage.html、/public/testis/testPage.html、/public/testicles/otherPage.html等,然后它们将被提供给浏览器。