Joel Fernando
Joel Fernando

Reputation: 997

Express: OpenSSL error: _tls_common.js:129 c.context.setCert(cert);

what i am trying to do is to use HTTPS with OpenSSL and HTTPS Core Module, here is my code:

App.js:

const url = config.mongoUrl;
const connect = mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });

connect.then(db => {
console.log("Connected correctly to server!");
}, err => console.log(err))

var app = express();

app.all('*', (req, res, next) => {
  if (req.secure) {
    return next();
  }
  else {
    res.redirect(307, 'https://' + req.hostname + ':' + app.get('secPort') + req.url);
  }

./bin/www:

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
app.set('secPort', port + 443);

/**
 * Create HTTP server.
 */
 
var options = {
  key: fs.readFileSync(__dirname+'/private.key'),
  cert: fs.readFileSync(__dirname+'/certificate.pem')
};

var secureServer = https.createServer(options, app);


/**
 * Listen on provided port, on all network interfaces.
 */

secureServer.listen(app.get('secPort'), () => {
   console.log('Server listening on port ',app.get('secPort'));
});
secureServer.on('error', onError);
secureServer.on('listening', onListening);
});

I created the certificate.pem, private.key and cert.csr with these commands in ./bin:

openssl genrsa 1024 > private.key
openssl req -new -key private.key -out cert.csr
openssl x509 -req -in cert.csr -signkey private.key -out certificate.pem

But when i do npm start nodemon gives me an error:

_tls_common.js:129
      c.context.setCert(cert);

Is there something i am doing wrong?

Upvotes: 2

Views: 1068

Answers (1)

Mr.Drew
Mr.Drew

Reputation: 1109

I followed the instructions here, but then also had to add a path.join() like:

const path = require('path');
var httpsOptions = {
  key: fs.readFileSync(path.join(__dirname, './https/key.pem')),
  cert: fs.readFileSync(path.join(__dirname, './https/cert.pem'))
};

Upvotes: 1

Related Questions