簡體   English   中英

將SSL添加到Node.js Koa Server?

[英]Add SSL to Node.js Koa Server?

我想用SSL加密我的Koa服務器。 使用常規的httpServer似乎很簡單,但我不知道如何使用Koa。 有人可以幫忙嗎?

我偶然發現了這個 使用節點包啟動https服務器並將其傳遞給Koa服務器實例.callback()就可以了。

Koa的文件

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;

看起來沒有明確的方法來做到這一點,但在我的服務器上運行Nginx是一個簡單的解決方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM