【问题标题】:how to specify basic routes with restify如何使用 restify 指定基本路由
【发布时间】:2017-06-17 09:40:00
【问题描述】:

以下作品

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

如何让它发挥作用?

【问题讨论】:

    标签: node.js routes restify


    【解决方案1】:

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

    /\/test\//
    

    【讨论】:

    • 是的,我在发布问题之前也尝试了正则表达式,但它没有用。我已经做了进一步的实验,很快就会发布答案。在我看来,restify 中路由的概念被打破了。
    【解决方案2】:

    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.htmllocalhost: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.htmllocalhost:8080/testicles/otherPage.html,并提供路径+相应文件存在于磁盘上,例如/public/test/testPage.html、/public/testis/testPage.html、/public/testicles/otherPage.html等,然后它们将被提供给浏览器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-13
      • 2015-12-28
      • 1970-01-01
      • 2017-05-14
      • 2012-05-27
      • 1970-01-01
      • 2014-05-04
      相关资源
      最近更新 更多