[英]how to specify basic routes with restify
以下作品
server.get('.*', restify.serveStatic({
'directory': './myPublic',
'default': 'testPage.html'
}));
我可以导航到http:localhost:8080,并在浏览器中显示/ myPublic内部的静态页面。
现在,我想更改路由,以便可以导航到http:localhost:8080 / test 。 因此我将上面的代码更改为
server.get('/test', restify.serveStatic({
'directory': './myPublic',
'default': 'testPage.html'
}));
不起作用,错误是
{
"code": "ResourceNotFound",
"message": "/test"
}
如何使其运作?
tl; dr;
我错误地假设url / test / whatever / path代表抽象的虚拟操作(类似于ASP.NET MVC路由),而不是服务器上的具体物理文件。 重新调整并非如此。
对于静态资源,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'
}));
该处理程序将与get请求localhost:8080 / test匹配,并将为磁盘上的默认页面public / test / testPage.html提供服务 。
为了使处理程序更加灵活,我可以使用RegEx
server.get(/\/test.*\/.*/, restify.serveStatic({
'directory': __dirname + '/myPublic',
'default': 'testPage.html'
}));
此RegEx表示匹配'/ test',后跟任何char(。)0或更多次(*),后跟斜杠(/),然后是0或更多次任何char。 示例可能是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等,然后将它们提供给浏览器。
看起来restify正在为路由寻找正则表达式,而不是字符串。 尝试这个:
/\/test\//
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.