有什么方法可以更改我的 Web 应用程序以侦听 HTTPS 而不是 HTTP。
我正在使用node.js/express。
我需要它来侦听 HTTPS,因为我正在使用地理定位,而 Chrome 不再支持地理定位,除非从 HTTPS 等安全上下文提供服务。
这是当前侦听 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 等。
相关阅读:
- 快速 + HTTPS https://timonweb.com/posts/running-expressjs-server-over-https/
- 表达::res.redirect() https://expressjs.com/en/api.html#res.redirect
- 在 Express 中重定向到 HTTPS https://expressjs.com/en/api.html#res.redirect
- 使用 Heroku 部署时使用 HTTPS https://stackoverflow.com/questions/7185074/heroku-nodejs-http-to-https-ssl-forced-redirect/23894573#23894573
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)