文档说路由处理程序从最具体到最不具体选择路由。因此,您可以使用 /api/v1/ 之类的东西预先修复您的 api 路由,然后不以 /api/v1/ 开头的所有其他内容都将被路由到由 inert 丢弃的静态文件。
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}`)
})
})