Enabling HTTPS on express.js

前端 未结 7 1115
栀梦
栀梦 2020-11-22 08:44

I\'m trying to get HTTPS working on express.js for node, and I can\'t figure it out.

This is my app.js code.

var express = require(\'exp         


        
7条回答
  •  礼貌的吻别
    2020-11-22 09:39

    In express.js (since version 3) you should use that syntax:

    var fs = require('fs');
    var http = require('http');
    var https = require('https');
    var privateKey  = fs.readFileSync('sslcert/server.key', 'utf8');
    var certificate = fs.readFileSync('sslcert/server.crt', 'utf8');
    
    var credentials = {key: privateKey, cert: certificate};
    var express = require('express');
    var app = express();
    
    // your express configuration here
    
    var httpServer = http.createServer(app);
    var httpsServer = https.createServer(credentials, app);
    
    httpServer.listen(8080);
    httpsServer.listen(8443);
    

    In that way you provide express middleware to the native http/https server

    If you want your app running on ports below 1024, you will need to use sudo command (not recommended) or use a reverse proxy (e.g. nginx, haproxy).

提交回复
热议问题