繁体   English   中英

使用 node.js/Express 从 HTTP 重定向到 HTTPS

[英]Redirect from HTTP to HTTPS using node.js/Express

有什么方法可以更改我的网络应用程序以侦听 HTTPS 而不是 HTTP。 我正在使用 node.js/express。

我需要它来侦听 HTTPS,因为我正在使用地理定位,除非从安全上下文(例如 HTTPS)提供服务,否则 Chrome 不再支持它。

这是当前侦听 HTTP 的当前“./bin/www”文件。

#!/usr/bin/env node

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

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


var server = http.createServer(app)

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


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

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

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

  return false;
}

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;
  }
}


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

是的,有办法。 首先,生成一个自签名证书:

openssl req -nodes -new -x509 -keyout server.key -out server.cert

然后,借助 Node 的 HTTPS 库,通过 HTTPS 提供服务:

// imports
const express = require('express');
var fs = require('fs');
const http = require('http');
const https = require('https');
const app = require('./path/to/your/express/app');

// HTTPS server
const httpsServer = https.createServer({
    key: fs.readFileSync('server.key'),
    cert: fs.readFileSync('server.cert')
}, app);
httpsServer.listen(443, () => console.log(`HTTPS server listening: https://localhost`));

最后,使用最小的 HTTP 服务器来监听对同一个域的请求并重定向它们:

// redirect HTTP server
const httpApp = express();
httpApp.all('*', (req, res) => res.redirect(300, 'https://localhost'));
const httpServer = http.createServer(httpApp);
httpServer.listen(80, () => console.log(`HTTP server listening: http://localhost`));

当然,这是最小的设置。 对于生产,您将使用不同的证书,并将localhost替换为您将从req生成的动态域名,并且您可能不想使用端口 80 和 443 等。

相关阅读:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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