使用RESTIFY提供静态文件

问题描述 投票:29回答:7

我正在学习使用Node.js.目前,我有一个如下所示的文件夹结构:

index.html
server.js
client
  index.html
  subs
    index.html
    page.html
res
  css
    style.css
  img
    profile.png
  js
    page.js
    jquery.min.js

server.js是我的网络服务器代码。我使用node server.js从命令行运行它。该文件的内容是:

var restify = require('restify');

var server = restify.createServer({
    name: 'Test App',
    version: '1.0.0'
});

server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());

server.get('/echo/:name', function (req, res, next) {
    res.send(req.params);
    return next();
});

server.listen(2000, function () {
    console.log('%s running on %s', server.name, server.url);
});

如您所见,此服务器依赖于RESTIFY。我被告知必须使用RESTIFY。但是,我无法弄清楚如何提供静态文件。例如,如何在我的应用程序中为* .html,* .css,* .png和* .js文件提供服务?

谢谢!

node.js restify
7个回答
43
投票

来自documentation

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

但这将搜索./public/docs/public/目录中的文件。 我更喜欢在这里使用__dirname键:

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

__dirname的值等于脚本文件目录路径,它假定也是一个文件夹,其中是public目录。

现在我们将所有/public/.*网址映射到./public/目录。


8
投票

根据我目前的restify版本(v5.2.0)

serveStatic已被移入plugins,因此代码将是这样的

server.get(
  /\/(.*)?.*/,
  restify.plugins.serveStatic({
    directory: './static',
  })
)

上面的语法将为文件夹static上的静态文件提供服务。所以你可以获得像http://yoursite.com/awesome-photo.jpg这样的静态文件

出于某种原因,如果你想在特定的路径下提供静态文件,比如这个http://yoursite.com/assets/awesome-photo.jpg

代码应该重构为此

server.get(
  /\/assets\/(.*)?.*/,
  restify.plugins.serveStatic({
    directory: `${app_root}/static`,
    appendRequestPath: false
  })
)

上面的选项qazxsw poi意味着我们不将qazxsw poi路径包含在文件名中


4
投票

从Restify 7路线appendRequestPath: false,所以如果你想让assets服务文件no longer take full regexes,你的代码现在看起来像这样:

/public/stylesheet.css

这是因为Restify 7有一个新的(可能更快的)路由后端:./public/stylesheet.css


2
投票

这就是我如何在restify中提供静态文件

server.get('/public/*', restify.plugins.serveStatic({
  directory: __dirname,
}))

公共访问路径将是:example.com/public/docs/index.html


1
投票

我刚刚遇到这个问题,所以虽然这可能对你没有帮助,但它可以帮助那些遇到麻烦的人。

当您将Restify声明为find-my-way时,serveStatic方法将位于plugins对象中,因此使用server.get(/\/public\/docs\/?.*/, restify.plugins.serveStatic({ directory: __dirname, default: 'index.html' })); 将悄然失败。访问该方法的正确方法是const restify = require('restify');

您可以在此处找到更新文档:restify.serveStatic


0
投票
restify.plugins.serveStatic

0
投票

试试这个:这里的视图是一个静态资源目录名

http://restify.com/docs/plugins-api/#serve-static
© www.soinside.com 2019 - 2024. All rights reserved.