Reputation: 195
I'm new to Hapi and Javascript and I'm trying to show a page in the browser. I have an main.html file that i want to be displayed as soons as we enter the first page, but with the code like it is I always get the error
"{"statusCode":500,"error":"Internal Server Error","message":"An internal server error occurred"}"
How can I display an html file?
The js file:
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 3000 });
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply.view('main.html');
}
});
server.route({
method: 'GET',
path: '/{name}',
handler: function (request, reply) {
reply('Hello, ' + encodeURIComponent(request.params.name) + '!');
}
});
server.start(function () {
console.log('Server running at:', server.info.uri);
});
Upvotes: 4
Views: 5698
Reputation: 461
hapi 9.0.0
and later require the vision for template rendering support. With vision, you’re decorating the reply
interface with a view
method that allows you to send HTML responses:
Your setup would look like this:
var Hapi = require('hapi')
var Vision = require('vision')
var Handlebars = require('handlebars')
// create new server instance
var server = new Hapi.Server()
// register vision to your server instance
server.register(Vision, function (err) {
if (err) {…}
// configure template support
server.views({ // config here
})
})
And then you can reply HTML like this:
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
var data = { message: 'Hello from Future Studio' }
reply.view('index', data)
}
})
You can follow also follow this tutorial:
https://futurestud.io/tutorials/hapi-how-to-render-views
Hope that helps!
Upvotes: 0
Reputation: 3751
If you are using hapi 9.x.x you need to load vision plugin to be able to use reply.view method. See docs here https://github.com/hapijs/vision
Upvotes: 0
Reputation: 1721
Have you set up the view config for the server? In the docs they say you require a view engine (like handlebars / swig).
If not maybe you could try serving a file with the absolute path
var path = require('path');
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply.file(path.join(__dirname, '../../../path/to/main.html'));
}
});
Upvotes: 2