A single-page hapi application using an inert plugin does not serve the api route

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

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

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

Basically, I would like both a static file and a json api for the server. I know how to do it in express, but I don’t know how with hapi. delimma: if I use only hapi, it does not serve the static file, and if I use hapi + is inert, it will not use the api route.

solutions????

0
hapijs
source share
1 answer

The documentation states that the route handler selects the route from the most specific to the least specific. Thus, you can pre-fix your api routes with something like / api / v 1 /, and then everything else that does not start with / api / v 1 / will be redirected to static files expanded with inert ones.

Hapi.js Routing Documentation:

When determining which handler is used for a particular request, hapi looks for paths in order from most specific to least specific. This means that if you have two routes: one with the track /filename.jpg and the second route /filename.{ext}, the request / filename.jpg will correspond to the first route, and not the second. This also means that the route with the trace / {files *} will be the last route checked 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}`) }) }) 
0
source share

All Articles