[英]How to use Hapi.js to serve a static HTML index
With express.js i can do this 使用express.js我可以做到这一点
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = 9200;
var path = require('path');
var options = {
index: "html/index.html"
};
app.use('/', express.static('res', options));
server.listen(port);
console.log("Listening on port " + port);
How do i achieve the same thing using Hapi.js? 我如何使用Hapi.js实现同样的目标?
I have tried some things also with inertjs but I can't seem to find the correct way. 我也尝试过一些与惰性相关的东西,但我似乎无法找到正确的方法。 Does anyone have experience with it?
有人有经验吗?
Found my way to this implementation, but im getting TypeErrors: TypeError: Cannot read property 'register' of undefined 找到了我的实现方式,但是我得到了TypeErrors:TypeError:无法读取未定义的属性'register'
server.register(require('inert'), (err) => {
if (err) {
throw err;
}
server.route({
method: 'GET',
path: '/index',
handler: function (request, reply) {
reply.file('C:/blabla/html/index.html');
}
});
});
In detail, you just have to call reply.file() 详细地说,你只需要调用reply.file()
This will not work with hapi 17 because of the major change in the request system 由于请求系统发生了重大变化,这对hapi 17无效
server.route({
method: 'GET',
path: '/picture.jpg',
handler: function (request, reply) {
reply.file('/path/to/picture.jpg');
}
});
Fixed by using Hapi@16.xx and Inert@4.xx and using Ernest Jones answer. 通过使用Hapi@16.xx和Inert@4.xx以及使用Ernest Jones答案进行修复。
For anyone dealing with this problem in the future here is my complete change: 对于将来处理此问题的任何人来说,这是我完全的改变:
const Hapi = require('hapi');
const Inert = require('inert');
const server = new Hapi.Server();
server.connection({port: 9200});
server.register(Inert, (err) => {
if (err) {
throw err;
}
server.route({
method: 'GET',
path: '/index',
handler: function (request, reply) {
reply.file('/res/html/index.html');
}
});
server.route({
path: "/res/{path*}",
method: "GET",
handler: {
directory: {
path: "./res",
listing: false,
index: false
}
}});
});
server.start();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.