首页 > 解决方案 > SSL 在基于 Express 的 HTTPS-Server Lib 中不起作用

问题描述

我已经基于 Express 制作了自己的 HTTPS-Server Lib,一切正常,只是我无法通过 SSL 获取给定的网站。我已经制作了这样的自签名证书,并添加了“localhost”或“localhost:3000”(我也尝试了 443 标准端口)作为通用名称:

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out certificate.pem -days 365 -nodes

这是我的课:

export class HttpsServer {

    private _serverInstance: express.Application = express();

    constructor(port: number, options: Options) {
        this.init(port, options);
    }

    init(port: number, options: Options) {
        https.createServer(options.https, this._serverInstance);
        this._serverInstance.use(cors(options.cors));
        if (!!options.directory) {
            this._serverInstance.use(express.static(options.directory));
        }
        this.listen(port);
    }

    get(route: string, handler: RequestHandler) {
        this._serverInstance.get(route, handler);
    }

    listen(port: number) {
        this._serverInstance.listen(port);
    }
}

这是我的实例:

const options: Options = {
  cors: {
    origin: ['*']
  },
  https: {
    key: fs.readFileSync('./certs/key.pem', 'utf8'),
    cert: fs.readFileSync('./certs/certificate.pem', 'utf8'),
  },
  directory: './httpdocs'
};

const currentHandler: RequestHandler = function handler (req, res) {
  console.log(req.route)
  // res.send('... registered ' + req.route.stack[0].method + '-request on route ' + req.route.path)
};

function bootstrap() {
  const server = new HttpsServer(3000, options);

  server.get('/', currentHandler);
}

bootstrap();

失眠 说:

error:1408F10B:SSL routines:ssl3_get_record:wrong version number

火狐 说:

SSL_ERROR_RX_RECORD_TOO_LONG

通过 HTTP,站点是可见的。我究竟做错了什么?谢谢

编辑解决方案:

init(httpPort: number, httpsPort: number, options: Options) {
        const httpServer = http.createServer(this._serverInstance);
        const httpsServer = https.createServer(options.https, this._serverInstance);

        this._serverInstance.use(cors(options.cors));
        if (!!options.directory) {
            this._serverInstance.use(express.static(options.directory));
        }

        httpServer.listen(httpPort);
        httpsServer.listen(httpsPort);
    }

我需要一个名为 httpsServer 的 const 和一个监听方法。Http/Https也需要不同的端口...

标签: node.jsexpresssslhttps

解决方案


推荐阅读