将所有请求HTTP重定向到HTTPS

时间:2016-12-14 18:37:52

标签: angular express

我有一个使用express运行的角度2应用程序,我想将所有请求http重定向到https,我从网上查看一些教程,但没有人工作。

我的应用程序托管在Heroku上。

我有两个用于express的配置文件:

服务器/ 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 }

服务器/ 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);
}

1 个答案:

答案 0 :(得分:0)

以下是我使用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)
});

我不熟悉将应用程序部署到Heroku,但我想,这将是一个类似的过程。如果你需要两个快递应用程序,我不是百分百确定,但无论如何我添加了一个http和https。