使用restify提供静态文件(node.js)

ope*_*sas 24 http node.js restify

我有以下代码:

app.js

[...]

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

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

我有以下文件结构

app.js
public/
  index.html
Run Code Online (Sandbox Code Playgroud)

所以我尝试浏览:

http://localhost:1337/docs/public/index.html
Run Code Online (Sandbox Code Playgroud)

我明白了

{
  code: "ResourceNotFound",
  message: "/docs/public/index.html"
}
Run Code Online (Sandbox Code Playgroud)

我尝试了几种变体,但似乎没有一种变化.

我敢肯定它应该是非常明显的我错过了

rob*_*lep 20

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

  • 我发现得到了很好的记录. (29认同)

小智 8

  1. directory选项是整个路径的前缀.
  2. 在Restify的更高版本中,相对路径无法正常工作(我测试了2.6.0-3,2.8.2-3 - 它们都产生了NotAuthorized错误)

解决方案现在变为:

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

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


小智 6

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

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