将 SSL 添加到 Node.js Koa 服务器?

Add SSL to Node.js Koa Server?

我想用 SSL 加密我的 Koa 服务器。使用常规的 httpServer 似乎很简单,但我不知道如何使用 Koa 来做到这一点。有人能帮忙吗?

看起来没有明确的方法可以做到这一点,但是 运行 我的服务器上的 Nginx 是一个简单的解决方法。

我偶然发现了 this。使用节点包启动 https 服务器并将其传递给 Koa 服务器实例 .callback() 就可以了。

Koa's doc

var fs = require('fs');
var path = require('path');
var http = require('http');
var https = require('https');

var Koa = require('koa');
var server = new Koa();

// add main routes

// the following routes are for the authorisation challenges
// ... we'll come back to this shortly
var acmeRouter = require('./acme-router.js');
server
  .use(acmeRouter.routes())
  .use(acmeRouter.allowedMethods());

var config = {
  domain: 'example.com',
  http: {
    port: 8989,
  },
  https: {
    port: 7979,
    options: {
      key: fs.readFileSync(path.resolve(process.cwd(), 'certs/privkey.pem'), 'utf8').toString(),
      cert: fs.readFileSync(path.resolve(process.cwd(), 'certs/fullchain.pem'), 'utf8').toString(),
    },
  },
};

let serverCallback = server.callback();
try {
  var httpServer = http.createServer(serverCallback);
  httpServer
    .listen(config.http.port, function(err) {
      if (!!err) {
        console.error('HTTP server FAIL: ', err, (err && err.stack));
      }
      else {
        console.log(`HTTP  server OK: http://${config.domain}:${config.http.port}`);
      }
    });
}
catch (ex) {
  console.error('Failed to start HTTP server\n', ex, (ex && ex.stack));
}
try {
  var httpsServer = https.createServer(config.https.options, serverCallback);
  httpsServer
    .listen(config.https.port, function(err) {
      if (!!err) {
        console.error('HTTPS server FAIL: ', err, (err && err.stack));
      }
      else {
        console.log(`HTTPS server OK: http://${config.domain}:${config.https.port}`);
      }
    });
}
catch (ex) {
  console.error('Failed to start HTTPS server\n', ex, (ex && ex.stack));
}

module.exports = server;