Migrating HTTPS server from Express to Hapi

时光总嘲笑我的痴心妄想 提交于 2019-12-12 02:23:21

问题


I'm trying to migrate an HTTPS server from Express to Hapi. The server is running fine on Express, but when I try to run it in Hapi I get messages saying "Invalid server options" and "TLS is not allowed".

This is my (simplified) code with Express:

var fs = require('fs');
var https = require('https');
var app = require('express')();
var options = {
   key: fs.readFileSync('server.key'),
   cert: fs.readFileSync('server.crt')
};

app.get('/', function (req, res) {
   res.send('Hello World!');
});

https.createServer(options, app).listen(8081);

And this is my (simplified) code with Hapi:

var fs = require('fs');
var Hapi = require('hapi');

var options = {
    tls: {
       key: fs.readFileSync('server.key'),
       cert: fs.readFileSync('server.crt')
    }
};
var server = new Hapi.Server(options);

server.connection({ host: 'localhost', port: 8081 });

server.route({
    method: 'GET',
    path: '/', 
    handler: function (request, reply) {
        return reply('Hello world!');
    }
});

server.start();

I'm using a self-signed certificate, but I guess that should be fine? It does work in Express.


回答1:


Your code looks pretty close. I believe all you have to do to get Hapi to use your certificate and key is to just move it over to the server.connection call, such as:

server.connection({
  host: 'localhost', 
  port: 8081,
  tls: {
    key: fs.readFileSync('server.key'),
    cert: fs.readFileSync('server.crt')
  }
});


来源:https://stackoverflow.com/questions/38530079/migrating-https-server-from-express-to-hapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!