如何使用 restify 指定基本路由

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"
}

如何让它发挥作用?

看起来 restify 正在寻找路由的正则表达式,而不是字符串。试试这个:

/\/test\//

tl;dr;

我错误地假设 url /test/whatever/path 表示抽象的虚拟操作(类似于 ASP.NET MVC 路由),而不是具体的服务器上的物理文件。 restify 不是这种情况。

restify 的工作原理是,对于静态资源,无论您在 url 上键入什么,它都必须存在于服务器的磁盘上,从 'directory' 中指定的路径开始。 所以当我请求 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'
}));

此正则表达式表示匹配“/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, 等等然后它们将被提供给浏览器。