HAPI JS Node js创buildhttps服务器

如何创buildhapi httphttps服务器,同时使用相同的路由监听80和443?

(我需要一个服务器,应该在http和https上运行完全相同的API)

@codelion给出了一个很好的答案,但是如果你仍然想要在多个端口上进行监听,你可以传递多个configuration来进行连接。

 var server = new Hapi.Server(); server.connection({ port: 80, /*other opts here */}); server.connection({ port: 8080, /*other opts, incl. ssh */ }); 

但是要再次注意,开始贬低http连接将是一件好事。 谷歌和其他人将很快开始标记他们不安全。 另外,用nginx或者其他东西来实际处理SSL可能是一个好主意,而不是节点应用本身。

在应用程序上直接处理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'); }); 

您可以将所有http请求redirect到https:

 if (request.headers['x-forwarded-proto'] === 'http') { return reply() .redirect('https://' + request.headers.host + request.url.path) .code(301); } 

查看https://github.com/bendrucker/hapi-require-https了解更多详情。

访问链接: 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); }); 

对于hapi新版本

 var Hapi = require('hapi'); var server = new Hapi.Server(); server.connection({ port: app.config.server.port }); 

您也可以使用local-ssl-proxy npm软件包将本地HTTPS代理到HTTP。 仅限本地开发。

我正在寻找这样的东西,发现了https://github.com/DylanPiercey/auto-sni它有一个快车,Koa,哈比(未经testing)

它基本上是基于letsencrypt证书并使用自定义侦听器加载hapi服务器。

还没有尝试过。