0
点赞
收藏
分享

微信扫一扫

node.js编写反向代理转发https

鱼满舱 2023-01-01 阅读 78

node.js编写反向代理转发https

const crypto = require("crypto");
const md5 = function (str) {
const md5 = crypto.createHash('md5');
md5.update(str);
return md5.digest('hex');
};
const fs = require("fs");
const url = require("url");
const path = require("path");
const http = require("https");
const options = {
key: fs.readFileSync('./cert/cert.key'), //密钥路径
cert: fs.readFileSync('./cert/cert.cer')
};
const server = http.createServer(options);
server.on('request', (req, res) => {
proxy(req, res);
});

server.listen(443, "0.0.0.0", (error) => {
if (error) {
console.log('服务启动失败', error);
return;
}
console.log('https 服务启动成功');
});

function replaceHTML(headers, bData) {
if (headers['content-type'] === 'text/html; charset=utf-8') {
var sHTML = bData.toString('utf-8');
sHTML = sHTML.replace('</head>', '</head><script src="/test.js"></script>');
return sHTML;
}
return bData;
}

function proxy(req, res) {
const options = {};
options.method = req.method;
options.host = '23.220.192.115';
options.headers = req.headers;
options.headers['accept-encoding'] = '';
options.path = req.url;
const urlinfo = url.parse(req.url);
const extname = path.extname(urlinfo.pathname);
const savefile = path.join('data', urlinfo.pathname);
const exts = ['.jpg', '.png', '.css', '.ico', '.map', '.ttf', '.mi', '.js'];
const isStatic = req.method === 'GET' && urlinfo.query === null && exts.indexOf(extname) >= 0;
if (isStatic) {
try {
const stat = fs.statSync(savefile);
if (stat.isFile()) {
try {
const json = JSON.parse(fs.readFileSync(savefile + '.json'));
res.writeHead(200, json.headers);
res.end(replaceHTML(json.headers, fs.readFileSync(savefile)));
} catch (ex) {
res.end(replaceHTML({}, fs.readFileSync(savefile)));
}
return;
}
} catch (ex) {
//console.log(ex);
}
}
console.log(req.method, req.url);
const r = http.request(options, (response) => {
res.writeHead(response.statusCode, response.headers);
const bfs = [];
response.on('data', (bf) => {
// 收到服务端回复的数据
bfs.push(bf);
});
response.on('end', () => {
const bf = Buffer.concat(bfs);
if (response.statusCode === 200 && isStatic) {
fs.mkdirSync(path.dirname(savefile), {recursive: true});
fs.writeFileSync(savefile, bf);
const json = {};
json.headers = response.headers;
fs.writeFileSync(savefile + '.json', JSON.stringify(json));
}
// 转发给浏览器
res.end(replaceHTML(response.headers, bf));
});
});
req.on('data', (d) => {
// 收到浏览器的请求数据,并转发到后端服务器
r.write(d);
});
req.on('end', () => {
r.end();
});
}

自动生成静态文件、修改html文件

 

举报

相关推荐

0 条评论