2015-11-01 54 views
1

我已經通過http://hapijs.com/tutorials/serving-files使用hapi中的相對路徑訪問靜態文件

但它沒有幫助我。

我有一個文件a.js在項目的根目錄中的靜態目錄。

我已將relativePath配置爲膠合配置,與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錯誤。

我錯過了什麼?

+0

我的答案是否奏效? –

回答

0

您需要更改代碼的發球路線以下

server.route({ 
    method: 'GET', 
    path: '/a.js', 
    handler: function (request, reply) { 
     reply.file(a.js'); 
    } 
}); 
1

註冊的inert插件的正確途徑,並允許您爲靜態文件。

您有多個選項來爲您的a.js文件提供服務,例如使用通配符路由參數爲動態方法提供各種JS文件。內handler你需要的路徑設置爲您的JS目錄和惰性會爲給定的搜索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

0

爲您服務,需要設置你的路由這樣的目錄:

{ 
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,() => {});