Reputation: 59
I have gone through http://hapijs.com/tutorials/serving-files
But it didn't help me out.
I have a file a.js
in a static directory in the root of the project.
I have configured relativePath
as glue configuration as inert
plugin that is in the root directory of the project.
plugins: {
'vision': {},
'inert': {
routes: {
files: {
relativeTo: Path.join(__dirname, 'static')
}
}
},
'visionary': {
engines: {
// other plugins
I have a server route as follows:
{
method: 'GET',
path: '/a.js',
handler: {
file : 'a.js'
}
}
But when I try to access http://localhost:3000/a.js
, it throws a 404 error.
What am I missing?
Upvotes: 3
Views: 2274
Reputation: 197
To serve a directory you need to set your routes like this:
{
path: '/{param*}',
method: 'GET',
config: {
handler: {
directory: {
path: path.resolve('directory_path')
}
}
}
}
To serve a static file you can do in this way:
{
path: '/your_path',
method: 'GET',
config: {
handler: function(request, reply) {
return reply.file('your_pfile_path');
}
}
}
Don't forget to add on your server.js file the inert require and to register it.
var Inert = require('inert');
server.register(Inert, () => {});
Upvotes: 1
Reputation: 461
Registering the inert
plugin is the right way and allows you to serve static files.
You've multiple options to serve your a.js
file, like using a wildcard route parameter for a dynamic approach to serve various JS files. Within the handler
you'd need to set the path to your JS directory and inert will search for the given file
within that folder:
server.route({
method: 'GET',
path: '/js/{file*}',
handler: {
directory: {
path: 'public/js'
}
}
})
You can also specify a static route to your JS file and serve it like this:
server.route({
method: 'GET',
path: '/mylocaljavascript.js',
handler: function (request, reply) {
// reply.file() expects the file path as parameter
reply.file('../path/to/my/localjavascript.js')
}
})
Hope that helps!
If you want more information about serving static files: https://futurestud.io/tutorials/hapi-how-to-serve-static-files-images-js-etc
Upvotes: 1
Reputation: 3751
You need to change code for serve route to the following
server.route({
method: 'GET',
path: '/a.js',
handler: function (request, reply) {
reply.file(a.js');
}
});
Upvotes: 0