HAPI JS Node js创建https服务器

13

如何创建一个使用 hapihttphttps 服务器,并在80和443端口上同时监听,并且具有相同的路由?

(我需要一个能够同时在http和https上运行,具有完全相同API的服务器)


您可以将所有的HTTP请求重定向到HTTPS。 - codelion
1
var http = require('http'), https = require('https'), express = require('express'), app = express(); http.createServer(app).listen(80); https.createServer({ ... }, app).listen(443); 我在想这样做可以吗?我们不能在hapi中实现吗? - Sathish
1
不,我的建议是为什么不将所有的http请求重定向到https呢?请参考https://github.com/bendrucker/hapi-require-https。 - codelion
嘿,Codelion,你知道有没有学习hapi js的电子书(免费/付费)吗?我想更多地了解hapi,我已经在文档中搜索过了,但如果我有一本菜谱或类似的东西,那么我就可以学到更多。 - Sathish
1
我不知道有这样的书,但你可以尝试一下我发现很有帮助的以下教程 - https://github.com/nelsonic/learn-hapi - codelion
让我们在聊天中继续这个讨论 - codelion
7个回答

24

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

我使用正确的域名尝试了相同的代码,但出现了ENOENT错误。你是否曾经因为权限或其他原因遇到过类似的问题? - agchou
1
端口号在1024以下是特权端口,需要root权限访问。 - Fernando
这是否意味着您需要使用root运行您的节点应用程序?这似乎是一个不好的主意。 - Vadorequest

7
您可以将所有HTTP请求重定向到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了解更多详情。

3
@codelion给出了一个很好的答案,但如果您仍然想在多个端口监听,可以为连接传递多个配置。
var server = new Hapi.Server();
server.connection({ port: 80, /*other opts here */});
server.connection({ port: 8080, /*other opts, incl. ssh */  });

但需要再次指出的是,开始逐步淘汰http连接可能是个好主意。Google和其他公司很快就会将它们标记为不安全。 此外,实际上使用nginx或其他工具处理SSL而非在node应用程序本身处理SSL也是一个好主意。

1
关于你最后一句话:你不想在 hapi 服务器和 nginx 代理服务器之间建立一个安全连接吗? - adam-beck
1
服务器连接 - 目前不可用。请使用多个服务器实例。 - Hydrock
很高兴看到5年前的答案仍然受到关注 :) 很可能这个问题和答案都已经过时了。 - Zlatko

1

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

0
回复所选答案:这个方法已经不再适用了,在17版本中被移除了。

https://github.com/hapijs/hapi/issues/3572

你得到:

TypeError: server.connection is not a function

解决方法是使用代理或创建两个 Hapi.Server() 实例。


0

0
我正在寻找类似的东西,发现了https://github.com/DylanPiercey/auto-sni,它有一个与Express、Koa、Hapi(未经测试)一起使用的示例用法。
它基本上是基于letsencrypt证书,并使用自定义监听器加载hapi服务器。
我还没有尝试过。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接