与没有反向代理的koa-sslify模块的Koa HTTPS连接

时间:2018-03-27 09:39:56

标签: ssl https koa

我尝试使用该模块https://www.npmjs.com/package/koa-sslify为Koa服务器建立HTTPS连接,但我收到错误“AssertionError:app.use()需要生成器函数”

'use strict';
var app = require('application'),
    enforceHttps = require('koa-sslify'),
    config = require('config'),
    fs = require('fs'),
    path = require('path'),
    routes = fs.readdirSync(path.join(__dirname, '../routing')).sort();

routes.forEach(function (route) {
    require('../routing/' + route);
});

// Force HTTPS on all page
app.use(enforceHttps({
  trustProtoHeader: true
}));

app.listen(config.server.port,config.server.host);

UPD:

我使用的是NGINX,因为它可能更好地工作并且使用更少的资源

1 个答案:

答案 0 :(得分:0)

以这种方式尝试,但最好将 NGINX 用作反向代理服务器

const Koa = require('koa');
const https = require('https');
const fs = require('fs');
const { default: enforceHttps } = require('koa-sslify');

const app = new Koa();

// Force HTTPS using default resolver
app.use(enforceHttps({
  port: 443
}));

// index page
app.use(ctx => {
  ctx.body = `hello world from ${ctx.request.url}`;
});

// SSL options
const options = {
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.crt')
}

// start the server
https.createServer(options, app.callback()).listen(443);