How do I setup a SSL certificate for an express.js server?

后端 未结 3 1958
北海茫月
北海茫月 2020-11-30 16:33

Before, in an older version of express, I could do this:

express.createServer({key:\'keyFile\', cert:\'certFile\'});

However, in newer vers

相关标签:
3条回答
  • 2020-11-30 17:13

    I was able to get SSL working with the following boilerplate code:

    var fs = require('fs'),
        http = require('http'),
        https = require('https'),
        express = require('express');
    
    var port = 8000;
    
    var options = {
        key: fs.readFileSync('./ssl/privatekey.pem'),
        cert: fs.readFileSync('./ssl/certificate.pem'),
    };
    
    var app = express();
    
    var server = https.createServer(options, app).listen(port, function(){
      console.log("Express server listening on port " + port);
    });
    
    app.get('/', function (req, res) {
        res.writeHead(200);
        res.end("hello world\n");
    });
    
    0 讨论(0)
  • 2020-11-30 17:19

    See the Express docs as well as the Node docs for https.createServer (which is what express recommends to use):

    var privateKey = fs.readFileSync( 'privatekey.pem' );
    var certificate = fs.readFileSync( 'certificate.pem' );
    
    https.createServer({
        key: privateKey,
        cert: certificate
    }, app).listen(port);
    

    Other options for createServer are at: http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener

    0 讨论(0)
  • 2020-11-30 17:23

    This is my working code for express 4.0.

    express 4.0 is very different from 3.0 and others.

    4.0 you have /bin/www file, which you are going to add https here.

    "npm start" is standard way you start express 4.0 server.

    readFileSync() function should use __dirname get current directory

    while require() use ./ refer to current directory.

    First you put private.key and public.cert file under /bin folder, It is same folder as WWW file.

    no such directory found error:

      key: fs.readFileSync('../private.key'),
    
      cert: fs.readFileSync('../public.cert')
    

    error, no such directory found

      key: fs.readFileSync('./private.key'),
    
      cert: fs.readFileSync('./public.cert')
    

    Working code should be

    key: fs.readFileSync(__dirname + '/private.key', 'utf8'),
    
    cert: fs.readFileSync(__dirname + '/public.cert', 'utf8')
    

    Complete https code is:

    const https = require('https');
    const fs = require('fs');
    
    // readFileSync function must use __dirname get current directory
    // require use ./ refer to current directory.
    
    const options = {
       key: fs.readFileSync(__dirname + '/private.key', 'utf8'),
      cert: fs.readFileSync(__dirname + '/public.cert', 'utf8')
    };
    
    
     // Create HTTPs server.
    
     var server = https.createServer(options, app);
    
    0 讨论(0)
提交回复
热议问题