在hapi中使用相对path访问静态文件
我已经通过http://hapijs.com/tutorials/serving-files
但它并没有帮助我。
我有一个文件a.js
在项目的根目录中的静态目录。
我已经将relativePath
configuration为胶合configuration作为项目根目录中的inert
插件。
plugins: { 'vision': {}, 'inert': { routes: { files: { relativeTo: Path.join(__dirname, 'static') } } }, 'visionary': { engines: { // other plugins
我有一个服务器路由如下:
{ method: 'GET', path: '/a.js', handler: { file : 'a.js' } }
但是,当我尝试访问http://localhost:3000/a.js
,它会引发404错误。
我错过了什么?
注册inert
插件是正确的方法,并允许您提供静态文件。
您有多个选项来为您的a.js
文件提供服务,例如使用通配符路由参数来实现dynamic方法来提供各种JS文件。 在handler
您需要将path设置为您的JS目录,惰性将search该file
夹中的给定file
:
server.route({ method: 'GET', path: '/js/{file*}', handler: { directory: { path: 'public/js' } } })
你也可以指定一个到你的JS文件的静态路由,并像这样提供它:
server.route({ method: 'GET', path: '/mylocaljavascript.js', handler: function (request, reply) { // reply.file() expects the file path as parameter reply.file('../path/to/my/localjavascript.js') } })
希望有所帮助!
如果你想了解更多关于静态文件的信息: https : //futurestud.io/tutorials/hapi-how-to-serve-static-files-images-js-etc
您需要将服务路线的代码更改为以下内容
server.route({ method: 'GET', path: '/a.js', handler: function (request, reply) { reply.file(a.js'); } });
为了提供一个目录,你需要像这样设置你的路由:
{ path: '/{param*}', method: 'GET', config: { handler: { directory: { path: path.resolve('directory_path') } } } }
要提供一个静态文件,你可以这样做:
{ path: '/your_path', method: 'GET', config: { handler: function(request, reply) { return reply.file('your_pfile_path'); } } }
不要忘记添加你的server.js文件的惰性要求,并注册它。
var Inert = require('inert'); server.register(Inert, () => {});