Migrating HTTPS server from Express to Hapi

2019-09-11 06:03发布

问题:

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')
  }
});