Reputation: 1345
I have read different threads and all answers there seem to not work properly, I am just trying to setup a hapijs server which is serving an angular application.
The index.html + other relevant files from ng build lie under the folder ./public. Now in the server.js I do this:
server.route({
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: Path.join(__dirname, 'public'),
redirectToSlash: true,
index: true,
}
}
});
This works well, but only for localhost:3000/ and if you do anything below (localhost:3000/admin for example) it will respond with a 404, which makes sense, cause there is no /admin in the public directory.
I have also tried:
server.route({
method: 'GET',
path: '/{param*}',
handler: {
file: './public/index.html'
}
});
Which does not work, as now the files under /public are not found anymore as they are also routed to the index.html.
Then I have tried to route /public/param* to the directory and /param* to index.html, hoping that now the public files would be "read" properly, but that didn't work as well.
What can I do to get this to work? I feel like I should have found 100 threads getting this to work, but I didn't see a single example which worked for me.
Thanks!
Upvotes: 0
Views: 368
Reputation: 1689
If you want to have every other route routed to index.html you can create a onPreResponse handler.
'use strict';
const Path = require('path');
const Inert = require('inert');
const Hapi = require('hapi');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost',
routes: {
files: {
relativeTo: Path.join(__dirname, 'public'),
},
},
});
await server.register(Inert);
server.route({
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: '.',
redirectToSlash: true,
lookupCompressed: true,
index: true,
},
},
});
server.ext('onPreResponse', (request, h) => {
const response = request.response;
if (!response.isBoom) {
return h.continue;
}
if (response.output.statusCode === 404) {
return h.file('index.html');
}
});
await server.start();
console.log('Server running on %', server.info.uri);
};
process.on('unhandledRejection', err => {
console.log(err);
process.exit(1);
});
init();
Upvotes: 1