0

I have an angular 2 application running with express and I would like to redirect all requests http to https, I follow some tutorials from the web but no one was working.

My application is hosted on Heroku.

I have two configuration files for express :

server/app.ts

import * as express from 'express';
import { json, urlencoded } from 'body-parser';
import * as path from 'path';
import * as cors from 'cors';
import * as compression from 'compression';

const app: express.Application = express();

app.disable('x-powered-by');

app.use(json());
app.use(compression());
app.use(urlencoded({ extended: true }));

if (app.get('env') === 'production') {

// in production mode run application from dist folder
 app.use(express.static(path.join(__dirname, '/../client')));
}

// catch 404 and forward to error handler
app.use(function(req: express.Request, res: express.Response, next) {
 let err = new Error('Not Found');
 next(err);
});

// production error handler
// no stacktrace leaked to user
app.use(function(err: any, req: express.Request, res: express.Response, next: express.NextFunction) {

  res.status(err.status || 500);
  res.json({
    error: {},
    message: err.message
  });
});

export { app }

server/bin/www.ts

#!/usr/bin/env node

/**
 * Module dependencies.
 */

import { app } from '../app';
import { serverPort } from '../config';
import * as http from 'http';

/**
 * Get port from environment and store in Express.
 */
const port = normalizePort(process.env.PORT || serverPort);
app.set('port', port);


/**
 * Create HTTP server.
 */
const 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): boolean | number {

  const normalizedPort = parseInt(val, 10);

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

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

  return false;
}

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

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

  const 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() {
  const addr = server.address();
  const bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  console.log('Listening on ' + bind);
}
Karim B
  • 54
  • 9

1 Answers1

0

Here is how I did it using nodeJS:

var app = express();
var httpapp = express();
options = {
       key: fs.readFileSync('.key'),
       cert: fs.readFileSync('.crt'),
       requestCert: true
}

var http = require('http').createServer(httpapp);
var server = require('https').createServer(options, app);
var port = process.env.PORT || 3000;

//Redirect http to https

httpapp.get('*', function(req, res) {
        res.redirect('https://127.0.0.1:' + port + req.url)
});

I am not familiar with deploying apps to Heroku, but I would imagine, this would be a similar process. I am not 100% sure if you need two express apps, but I added an http and https one anyway.

John F.
  • 154
  • 1
  • 10