使用惰性插件的hapi单页应用程序无法提供api路由 [英] hapi single page application using inert plugin doesn't serve up api route
问题描述
我正在尝试使用hapi和inert构建一个单页应用程序.
I am trying to build a single page application using hapi and inert.
我的示例代码在这里: https://github.com/7seven7lst/hapi-inert -测试
my example code is here: https://github.com/7seven7lst/hapi-inert-test
,然后根据这里的答案构建项目的基础 nodejs hapi单页
and the base of the project is built from the answer here nodejs hapi single page
基本上,我想将静态文件和api json数据都存储到前端.我知道如何做到这一点,但还没有弄清楚如何使用hapi. delimma是:如果仅使用hapi,则不会提供静态文件,如果使用hapi + inert,则不会提供api路由.
Basically I would like to both server static file and api json data to front end. I know how to do this in express, but haven't figure out how with hapi. the delimma is : if I use hapi only, it doesn't serve up static file, and if i use hapi+inert, it wont' serve up api route.
解决方案??
推荐答案
文档说,路由处理程序从最具体到最不具体选择路由.因此,您可以使用/api/v1/之类的前缀来预先确定您的api路由,然后所有不以/api/v1/开头的其他内容都将路由到由惰性抛出的静态文件中.
The documentation says that the route handler chooses the route from most specific to least specific. So you can pre-fix your api routes with something like /api/v1/ and then everything else that doesn't begin with /api/v1/ will get routed to static files dished up by inert.
在确定要用于特定请求的处理程序时,hapi会按从最具体到最不具体的顺序搜索路径.这意味着,如果您有两条路径,一条路径为/filename.jpg,第二条路径为/filename.{ext},则对/filename.jpg的请求将匹配第一个路由,而不是第二个.这也意味着,路径为/{files *}的路由将是最后测试的路由,并且仅在所有其他路由均失败时才匹配.
When determining what handler to use for a particular request, hapi searches paths in order from most specific to least specific. That means if you have two routes, one with the path /filename.jpg and a second route /filename.{ext} a request to /filename.jpg will match the first route, and not the second. This also means that a route with the path /{files*} will be the last route tested, and will only match if all other routes fail.
'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}`)
})
})
这篇关于使用惰性插件的hapi单页应用程序无法提供api路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!