Created
August 2, 2022 09:26
-
-
Save luo3house/bff89dedc7703adb6819f1014056eca3 to your computer and use it in GitHub Desktop.
HTTPS 反代本地开发环境,避免线上后端 CORS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Step 1: 修改 /etc/hosts,把 CORS 合法域名指向本机 | |
// Step 2: 当前目录准备该域名的证书 tls.crt | |
// Step 3: 当前目录准备该域名的证书 tls.key | |
// Step 4: 修改 TARGET 为本地开发环境的 URL | |
// Step 5: node server.js | |
var http = require('http'), https = require('https'), fs = require('fs') | |
var TARGET = 'http://localhost:8080' | |
var PORT = 443 | |
var server = https.createServer({ | |
cert: fs.readFileSync('tls.crt'), | |
key: fs.readFileSync('tls.key'), | |
}) | |
server.on('request', function(req, rsp) { | |
var url = TARGET + req.url | |
var proxy = http.request(url, function(response) { | |
for (var key in response.headers) { | |
rsp.setHeader(key, response.headers[key]) | |
} | |
response | |
.on('data', function (chunk) { rsp.write(chunk) }) | |
.on('end', function () { rsp.end() }) | |
}) | |
proxy.once('error', function (e) { | |
console.error(e.toString()) | |
rsp.writeHead(500).end() | |
}) | |
// if client close response unexpectedly | |
rsp.on('close', function () { proxy.destroy()}) | |
req.pipe(proxy) | |
}) | |
server.listen(PORT) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment