2017-07-02 36 views
0

我正在嘗試使用hapi和惰性構建單頁應用程序。使用惰性插件的hapi單頁應用程序不提供api路線

我的示例代碼是在這裏:https://github.com/7seven7lst/hapi-inert-test

和項目的基礎就是從這裏nodejs hapi single page

答案內置基本上,我想這兩個服務器的靜態文件和API JSON數據到前端。我知道如何做到這一點,但沒有弄清楚如何與hapi。 delimma是:如果我只使用hapi,它不提供靜態文件,如果我使用hapi + inert,它不會'提供api路由。

解決方案????

回答

0

該文檔說,路由處理程序選擇從最具體到最不具體的路線。所以你可以用/ api/v1 /之類的東西來預先修復你的api路由,然後其他所有不以/ api/v1 /開頭的東西都會被路由到靜態文件。

Hapi.js Routing Documentation:

在確定要使用什麼處理程序對於特定的請求,搜索HAPI爲了從最具體到最不具體的路徑。這意味着如果您有兩條路徑,一條路徑爲/filename.jpg,另一條路徑爲/filename.{ext,則對/filename.jpg的請求將匹配第一條路由,而不是第二條。這也意味着路徑/ {files *}將成爲最後測試的路由,並且只有在所有其他路由都失敗的情況下才會匹配。

'use strict' 

const Hapi= require('Hapi') 

// Config 
var config= { 
    connection: {port: 3000, host: 'localhost'} 
} 

const server= new Hapi.Server() 
server.connection(config.connection) 


const plugins= [ 
    // https://github.com/hapijs/inert 
    { register: require('inert'), options: {} }, 
] 

function setupRoutes() { 

    // Sample API Route 
    server.route({ 
     method: 'GET', 
     path: '/api/v1/Person/{name}', 
     handler: function (req, reply) { 
      reply('Hello, '+ encodeURIComponent(req.params.name)+ '!') 
     } 
    }) 

    // Web Server Route 
    server.route({ 
     method: 'GET', 
     path: '/{files*}', 
     // https://github.com/hapijs/inert#the-directory-handler 
     handler: {directory: {path: '../html_root', listing: false, index: true } } 
    }) 
} 

server.register(plugins, (err)=> { 
    if (err) {throw err} 

    // Initialize all routes 
    setupRoutes() 

    // Start the Server 
    server.start((err)=> { 
     if (err) {throw err} 
     server.log('info', `Server running at: ${server.info.uri}`) 
    }) 
}) 
相關問題