Is it possible to define a global base path in hapi

I want each hapi route to start with a prefix ( /api/1 ) without adding it to each route. Is it possible?

The following route should be accessible using the path /api/1/pets , not /pets

 const Hapi = require('hapi'); const server = new Hapi.Server(); server.route({ method: 'GET', path: '/pets' }) 
+5
source share
3 answers

It would be best to use a constant in the paths -

 server.route({ method: 'GET', path: constants.route.prefix + '/pets') }); 

and the constant is defined in the static file constants.js

0
source

It seems you cannot do this globally for the entire application. But it is possible to add prefixes for all routes defined inside the plugin:

 server.register(require('a-plugin'), { routes: { prefix: '/api/1' } }); 

Hope this helps.

Just in case, if you try to add a base path through events for new routes, this will not work.

+1
source

I do not see such an option in Hapi docs . However, I can offer you a small workaround. Make some function:

 function createRoutePath(routePath) { return `/api/1${routePath}`; } 

And then use it like this:

 server.route({ method: 'GET', path: createRoutePath('/pets') }); 

UPDATE: As another workaround, leave it as it is and configure the proxy server. For example nginx.

0
source

Source: https://habr.com/ru/post/1271529/


All Articles