我正在学习使用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.jsserver.js是我的code服务器代码。我使用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文件?
谢谢!
发布于 2013-10-09 20:17:52
来自文档
server.get(/\/docs\/public\/?.*/, restify.plugins.serveStatic({
directory: './public'
}));但这将搜索./public/docs/public/目录中的文件。
如果不想向其追加请求路径,请使用appendRequestPath: false选项。
我更喜欢在这里使用脏名键:
server.get(/\/public\/?.*/, restify.plugins.serveStatic({
directory: __dirname
}));__dirname的值等于脚本文件目录路径,假定它也是一个文件夹,其中是public目录。
现在我们将所有/public/.* urls映射到./public/目录。
现在也存在serveStaticFiles插件:
server.get('/public/*', // don't forget the `/*`
restify.plugins.serveStaticFiles('./doc/v1')
); // GET /public/index.html -> ./doc/v1/index.html file发布于 2017-10-11 11:22:26
根据我目前的版本(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
})
)上面的选项appendRequestPath: false意味着我们在文件名中不包含assets路径
发布于 2018-06-18 13:31:24
从Restify 7路由不再吃完全的雷克斯,所以如果您希望/public/stylesheet.css为文件./public/stylesheet.css提供服务,那么您的代码现在将如下所示:
server.get('/public/*', restify.plugins.serveStatic({
directory: __dirname,
}))这是因为Restify 7有一个新的(可能更快)的后端路由:找到-我的路。
https://stackoverflow.com/questions/19281654
复制相似问题