HAPI JS节点js创建https服务器

Sat*_*ish 13 node.js hapijs

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

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

Fer*_*ndo 20

直接在应用程序上处理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');
});
Run Code Online (Sandbox Code Playgroud)


cod*_*ion 7

您可以将所有http请求重定向到https:

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

有关更多详细信息,请访问https://github.com/bendrucker/hapi-require-https.


Zla*_*tko 3

@codelion 给出了一个很好的答案,但是如果您仍然想监听多个端口,您可以传递多个连接配置。

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

但再次注意,最好开始贬值 http 连接。谷歌和其他公司很快就会开始将它们标记为不安全。另外,使用 nginx 或其他东西实际处理 SSL 可能是一个好主意,而不是在节点应用程序本身上。