I'm writing an API on HapiJS, and wondering how to get a global prefix. For example, all requests should be made to:
https://api.mysite.com/v0/...
So I'd like to configure v0
as a global prefix. The docs (here) don't seem to mention it -- is there a good way to do this in HapiJS?
Matt Harrisson's answer is the hapi way to do it using plugins.
Alternatively if you don't want to create a plugin just to add a prefix, you can by hand, add the prefix to all your routes.
For instance I went for something like this:
Good point is that with something like this your can perform
express
-like mounting. ex:If you put your API routing logic inside a Hapi plugin, say
./api.js
:You register the plugin with a server and pass an optional route prefix, which will be prepended to all your routes inside the plugin:
You can verify this works by starting the server and visiting
http://localhost:3000/v0/hello
.you can always start your index.js like this
this way everywhere inside your code you'll have access to PREFIX
that's how you can access to PREFIX
console.log(PREFIX);
orvar name = PREFIX+ "_somename";
Take a look at hapi-auto-route. This plugin automaticaly register your routes from a directory
and add prefix to it:
I was able to get it working for all routes with