【发布时间】:2017-04-30 04:58:26
【问题描述】:
我有一个使用 express 运行的 angular 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);
}
【问题讨论】: