使用Restify(Node.js)提供静态文件服务

24

我有以下代码:

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

我尝试了几种变化,但似乎没有一种行得通。

我确定我错过了某些显而易见的东西。

3个回答

20

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


30
我发现 Restify 的文档非常糟糕。 - Chase Wilson

8
  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选项是关键! - Daniel Gray
似乎在OSX上有一个bug,阻止使用"./"语法,所以这是我唯一有效的方法。谢谢! - david.tanner

6
基于@NdeeJim的回答,如果有人想知道如何提供所有静态资源:
server.get(/\/?.*/, restify.plugins.serveStatic({
            directory: __dirname,
            default: 'index.html',
            match: /^((?!app.js).)*$/   // we should deny access to the application source
     }));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接