【问题标题】:serving static files with restify (node.js)使用 restify (node.js) 提供静态文件
【发布时间】:2013-03-06 00:33:17
【问题描述】:

我有以下代码:

app.js

[...]

server.get(/\/docs\/public\/?.*/, restify.serveStatic({
  directory: './public'
}));

server.listen(1337, function() {
  console.log('%s listening at %s', server.name, server.url);
});

我有以下文件结构

app.js
public/
  index.html

所以我尝试浏览:

http://localhost:1337/docs/public/index.html

我明白了

{
  code: "ResourceNotFound",
  message: "/docs/public/index.html"
}

我尝试了几种变体,但似乎都不起作用。

我确定这应该是很明显的我想念的东西

【问题讨论】:

    标签: node.js http restify


    【解决方案1】:

    restify 将使用directory 选项作为整个路由路径 的前缀。在您的情况下,它将寻找./public/docs/public/index.html

    【讨论】:

    • 我发现 restify 被记录得很糟糕。
    【解决方案2】:
    1. directory 选项是整个路径的前缀。
    2. 相对路径在更高版本的 Restify 中无法正常工作(我测试了 2.6.0-3、2.8.2-3 - 它们都产生 NotAuthorized 错误)

    现在的解决方案变成:

    server.get(/\/docs\/public\/?.*/, restify.serveStatic({
        directory: __dirname
    }));
    

    然后您的静态文件将需要位于./docs/public
    __dirname 是一个全局变量,包含你正在运行的脚本的绝对路径)

    【讨论】:

    • 这是为我做的!! __dirname 选项是关键!
    • OSX 似乎存在一个错误,阻止使用 ./ 语法,所以这是唯一对我有用的东西。谢谢!
    【解决方案3】:

    根据@NdeeJim 的回答,任何想知道如何提供所有静态资源的人:

    server.get(/\/?.*/, restify.plugins.serveStatic({
                directory: __dirname,
                default: 'index.html',
                match: /^((?!app.js).)*$/   // we should deny access to the application source
         }));
    

    【讨论】:

      猜你喜欢
      • 2013-10-19
      • 2013-10-17
      • 2013-06-10
      • 1970-01-01
      • 2014-07-20
      • 2014-02-11
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      相关资源
      最近更新 更多