如何创建一个使用 hapi 的 http
和 https
服务器,并在80和443端口上同时监听,并且具有相同的路由?
(我需要一个能够同时在http和https上运行,具有完全相同API的服务器)
如何创建一个使用 hapi 的 http
和 https
服务器,并在80和443端口上同时监听,并且具有相同的路由?
(我需要一个能够同时在http和https上运行,具有完全相同API的服务器)
在应用程序中直接处理https请求可能并不常见,但是Hapi.js可以在同一个API中处理http和https。
var Hapi = require('hapi');
var server = new Hapi.Server();
var fs = require('fs');
var tls = {
key: fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/example.com/cert.pem')
};
server.connection({address: '0.0.0.0', port: 443, tls: tls });
server.connection({address: '0.0.0.0', port: 80 });
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('Hello, world!');
}
});
server.start(function () {
console.log('Server running');
});
if (request.headers['x-forwarded-proto'] === 'http') {
return reply()
.redirect('https://' + request.headers.host + request.url.path)
.code(301);
}
var server = new Hapi.Server();
server.connection({ port: 80, /*other opts here */});
server.connection({ port: 8080, /*other opts, incl. ssh */ });
访问链接: http://cronj.com/blog/hapi-mongoose
这里有一个示例项目,可以帮助您解决此问题。
对于早于8.x版本的hapi:
var server = Hapi.createServer(host, port, {
cors: true
});
server.start(function() {
console.log('Server started ', server.info.uri);
});
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: app.config.server.port });
https://github.com/hapijs/hapi/issues/3572
你得到:
TypeError: server.connection is not a function
解决方法是使用代理或创建两个 Hapi.Server()
实例。