2017-07-02 35 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}`) 
    }) 
}) 
相关问题