用restify(node.js)提供静态文件
我有以下代码:
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" }
我尝试了几个变化,但没有一个似乎工作。
我相信它应该是我很想念的东西
restify
将使用directory
选项作为整个pathpath的前缀。 在你的情况下,它会寻找./public/docs/public/index.html
。
-
directory
选项是整个path的前缀。 - 在Restify的后续版本中,相对path不能正常工作(我testing了2.6.0-3,2.8.2-3,它们都产生了NotAuthorized错误)
现在解决scheme变成:
server.get(/\/docs\/public\/?.*/, restify.serveStatic({ directory: __dirname }));
然后你的静态文件将需要在./docs/public
。
( __dirname
是包含正在运行的脚本的绝对path的全局variables)
基于@ NdeeJim的回答,任何想知道如何服务所有静态资源的人:
server.get(/\/?.*/, restify.serveStatic({ directory: __dirname, default: 'index.html', match: /^((?!app.js).)*$/ // we should deny access to the application source }));