Node.js中localhost:300/443重定向至localhost的原因咨询
问题描述
我使用Node.js搭建网站,监听300端口(HTTP)和443端口(HTTPS),相关代码如下:
const fs = require('fs'); const https = require('https'); const http = require('http'); const app = require('../app'); const env = require(`../environment/${process.env.NODE_ENV}`); const httpServer = http.createServer((req, res) => { res.writeHead(301, { Location: `https://${req.headers.host.split(':')[0] + ':' + env.portHttps}${req.url}` }); res.end(); }).listen(env.portHttp); const options = { key: fs.readFileSync(env.key), cert: fs.readFileSync(env.cert), }; const httpsServer = https.createServer(options, app).listen(env.portHttps);
原本预期访问localhost:300或localhost:443时直接打开网站,但实际在Chrome中会重定向至https://localhost/,不清楚重定向的原因,同时疑惑既然会重定向,为何还要调用.listen(port)方法。另外我有Angular代理配置(如下),已知其作用,仅询问重定向原因:
{ "/": { "target": "https://localhost", "changeOrigin": true, "secure": false } }
问题解答
重定向原因
HTTP服务的强制重定向逻辑
你的HTTP服务(监听300端口)代码里明确写了重定向逻辑:只要收到HTTP请求,就返回301状态码,将请求跳转到对应的HTTPS地址。所以访问localhost:300时,会直接触发这个跳转。端口号被浏览器自动省略
如果你的env.portHttps配置的是443(HTTPS默认端口),拼接后的重定向地址是https://localhost:443,但浏览器会自动省略HTTPS的默认端口443,最终显示为https://localhost/,实际还是访问的443端口。Angular代理的间接作用
你的Angular代理目标是https://localhost(不带端口),开发服务器会把请求转发到这个地址,浏览器访问该地址时默认使用443端口,这也会让最终地址显示为https://localhost/。
关于.listen(port)的作用
- HTTP服务调用
.listen(300)是为了监听所有HTTP请求,执行重定向逻辑,完成从HTTP到HTTPS的引导,这是实现强制HTTPS访问的必要步骤。 - HTTPS服务调用
.listen(443)是为了提供实际的网站服务,所有重定向后的请求最终都会由这个服务处理。
内容的提问来源于stack exchange,提问作者vince
相关产品推荐
相关产品推荐

