问题描述
我正在尝试使用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.
'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路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!