简体   繁体   中英

how to set up a HTTPS server using express

I have an application using express.

I have a http server running but I would like to use a https server for more security.

I already generated my selfsigned.crt certificate and the key selfsigned.key using openssl (I'm on windows and I'm using visual studio code ). however, after trying during hours I didn't succeed.

I checked a lot of websites and its seems doable but I can't do it. (My project name is called carsapp that's why you will see it appears in the www file)

my app.js file:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');


var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');


var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});




module.exports = app;

and in my bin directory the www file:

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('carsapp:server');
var http = require('http');


/**
 * Get port from environment and store in Express.
 */

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

/**
 * Create HTTP server.
 */

 var server = http.createServer(app);




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

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

As you can see the http server works perfectly but I tried for https but I can't so here it is my code before trying for https.

You can enable https by including the https library and then pass the required certificates in as options, along with the express app.

const https = require('https');
const fs = require('fs');
const app = require('../app');

const options = {
  key: fs.readFileSync('./keyFile.key'),
  cert: fs.readFileSync('./certFile.crt')
};

const server = https.createServer(options, app);
server.listen(8000);

On a side note I happen to agree with @Quentin. If this app faces the world you might want to seriously consider using a reverse proxy.

I suggest making these changes to the 'www' file in your bin folder...

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('carsapp:server');
var https = require('https'); // <--- change to https
var fs = require('fs'); // <--- for loading the certificates

/** Load the certificate and key files using 'fs' */
const options = {
  key: fs.readFileSync('./keyFile.key'),
  cert: fs.readFileSync('./certFile.crt')
};

// The createServer function takes an extra argument.
var server = https.createServer(options, app);

// (continue with the rest of your code)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM