hapi single page application using inert plugin doesn't serve up api route

巧了我就是萌 提交于 2019-12-12 03:53:57

问题


I am trying to build a single page application using hapi and inert.

my example code is here: https://github.com/7seven7lst/hapi-inert-test

and the base of the project is built from the answer here nodejs hapi single page

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.

solutions????


回答1:


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.js Routing Documentation:

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}`)
    })
})


来源:https://stackoverflow.com/questions/44866806/hapi-single-page-application-using-inert-plugin-doesnt-serve-up-api-route

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!