我正在学习使用 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 文件?
谢谢!
最佳答案
来自 documentation :
server.get(/\/docs\/public\/?.*/, restify.plugins.serveStatic({
directory: './public'
}));
但这会搜索 ./public/docs/public/
目录中的文件。
如果您不想将请求路径附加到它,请使用 appendRequestPath: false
选项。
我更喜欢使用 __dirname关键在这里:
server.get(/\/public\/?.*/, restify.plugins.serveStatic({
directory: __dirname
}));
__dirname
的值等于脚本文件目录路径,假设也是一个文件夹,这里是public
目录。
现在我们将所有 /public/.*
url 映射到 ./public/
目录。
现在也存在serveStaticFiles插件:
server.get('/public/*', // don't forget the `/*`
restify.plugins.serveStaticFiles('./doc/v1')
); // GET /public/index.html -> ./doc/v1/index.html file
关于node.js - 使用 restify 提供静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19281654/