nodejs实现http与https服务;同时处理proxy代理的解决方案

javascript 复制代码
// nodejs服务提供的http协议示例
const http = require('http');
const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/html;charset=utf8' });
    res.end(Date.now() + ' == > http访问成功8080')
});
server.listen(8080, () => {
    console.log('服务已开启');
})
javascript 复制代码
// nodejs服务提供的https协议示例
const https = require('https');
const fs = require('fs');
const path = require('path');
const options = {
    key: fs.readFileSync(path.join(__dirname, './key.pem')),
    cert: fs.readFileSync(path.join(__dirname, './cert.pem')),
};
const server = https.createServer(options, (req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/html;charset=utf8' });
    res.end('https访问8081成功 == > ' + Date.now())
});
server.listen(8081, () => {
    console.log('服务已开启');
})
javascript 复制代码
// 正向代理 :如axios,http.proxy 用户直到,类似于梯子
var http = require('http');
var httpProxy = require('http-proxy')

// 创建代理服务器
let proxy = httpProxy.createProxyServer()

let server = http.createServer((req, res) => {
    proxy.web(req, res, {
        target: 'http://localhost:8080',
        // target: 'https://localhost:8081', // 并不能代理https
    })
})

server.listen(3000)
// server启动成功
server.on('listening', () => {
    console.log('http启动完成')
})

// 关闭HTTP服务器

server.on('close', () => {
    console.log('服务器关闭')
})
javascript 复制代码
// 反向代理 :解决用户请求的,用户不知道
let httpProxy = require('http-proxy')
let https = require('https');
const fs = require('fs');
const path = require('path');

const options = {
    key: fs.readFileSync(path.join(__dirname, './key.pem')),
    cert: fs.readFileSync(path.join(__dirname, './cert.pem')),
};

// 这是我们配置的域名,我们可以访问这些域名,拿到对应的结果
let hosts = {
    'as.cc': 'http://localhost:8080',
    // 'as.com': 'https://localhost:8081',// 也不支持https
}

// 创建代理服务器
let proxy = httpProxy.createProxyServer()

let server = https.createServer(options, (req, res) => {
    // 拿到host 访问对应的服务器
    let host = req.headers['host'].split(':')[0]
    console.log(666.789, host, hosts[host])
    proxy.web(req, res, {
        target: hosts[host] || 'https://localhost:8081'
    })
})

server.listen(3001)
// server启动成功
server.on('listening', () => {
    console.log('https启动完成')
})

// 关闭HTTPS服务器
server.on('close', () => {
    console.log('服务器关闭')
})
javascript 复制代码
// # nodejs原生实现转发http请求,方案一
const http = require("http");
const server = http.createServer();

server.on("request", (req, res) => {
    var { connection, host, ...originHeaders } = req.headers;
    var options = {
        "method": req.method,
        "hostname": "localhost",
        "port": "8080",
        "path": req.url,
        "headers": { originHeaders }
    }
    //接收客户端发送的数据
    var p = new Promise((resolve, reject) => {
        let postbody = [];
        req.on("data", chunk => {
            postbody.push(chunk);
        })
        req.on('end', () => {
            let postbodyBuffer = Buffer.concat(postbody);
            resolve(postbodyBuffer)
        })
    });
    //将数据转发,并接收目标服务器返回的数据,然后转发给客户端
    p.then((postbodyBuffer) => {
        let responsebody = []
        var request = http.request(options, (response) => {
            response.on('data', (chunk) => {
                responsebody.push(chunk)
            })
            response.on("end", () => {
                responsebodyBuffer = Buffer.concat(responsebody)
                res.setHeader('Content-Type', 'text/html;charset=utf-8');
                res.end(responsebodyBuffer);
            })
        })
        // 使用request的write方法传递请求体
        request.write(postbodyBuffer)
        // 使用end方法将请求发出去
        request.end();
    })
});
server.listen(3002, () => {
    console.log("runnng3002");
})
javascript 复制代码
// # nodejs原生实现转发http请求,方案二
const http = require('http');
const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/html;charset=utf8' });
    const options = {
        hostname: 'localhost',
        port: 8080,
        path: req.url,
        method: req.method
    };
    const proxyReq = http.request(options, (proxyRes) => {
        proxyRes.on('data', (chunk) => {
            res.write(chunk);
        });
        proxyRes.on('end', () => {
            res.end();
        });
    });
    proxyReq.on('error', (e) => {
        console.error(`请求遇到问题: ${e.message}`);
    });

    req.on('data', (chunk) => {
        proxyReq.write(chunk);
    });
    req.on('end', () => {
        proxyReq.setHeader('Content-Type', 'text/html;charset=utf-8');
        proxyReq.end();
    });
});

server.listen(3003, () => {
    console.log('服务器正在监听3003端口');
});
javascript 复制代码
// # nodejs原生实现转发https请求,方案一
const fs = require('fs');
const path = require('path');
let http = require('http');
let https = require('https');

const proxyoptions = {
    key: fs.readFileSync(path.join(__dirname, './key.pem')),
    cert: fs.readFileSync(path.join(__dirname, './cert.pem')),
};

const server = https.createServer(proxyoptions);

server.on("request", (req, res) => {
    var { connection, host, ...originHeaders } = req.headers;
    var options = {
        "method": req.method,
        // 随表找了一个网站做测试,被代理网站修改这里
        "hostname": "localhost",
        "port": "8080",
        "path": req.url,
        "headers": { originHeaders }
    }
    //接收客户端发送的数据
    var p = new Promise((resolve, reject) => {
        let postbody = [];
        req.on("data", chunk => {
            postbody.push(chunk);
        })
        req.on('end', () => {
            let postbodyBuffer = Buffer.concat(postbody);
            resolve(postbodyBuffer)
        })
    });
    //将数据转发,并接收目标服务器返回的数据,然后转发给客户端
    p.then((postbodyBuffer) => {
        let responsebody = []
        var request = http.request(options, (response) => {
            response.on('data', (chunk) => {
                responsebody.push(chunk)
            })
            response.on("end", () => {
                responsebodyBuffer = Buffer.concat(responsebody)
                res.setHeader('Content-Type', 'text/html;charset=utf-8');
                res.end(responsebodyBuffer);
            })
        })
        // 使用request的write方法传递请求体
        request.write(postbodyBuffer)
        // 使用end方法将请求发出去
        request.end();
    })
});
server.listen(3004, () => {
    console.log("runnng3004");
})
javascript 复制代码
// # nodejs原生实现转发https请求,方案一
const fs = require('fs');
const path = require('path');
let http = require('http');
let https = require('https');

const proxyoptions = {
    key: fs.readFileSync(path.join(__dirname, './key.pem')),
    cert: fs.readFileSync(path.join(__dirname, './cert.pem')),
};

const server = https.createServer(proxyoptions, (req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/html;charset=utf8' });
    const options = {
        hostname: 'localhost',
        port: 8080,
        path: req.url,
        method: req.method
    };
    const proxyReq = http.request(options, (proxyRes) => {
        proxyRes.on('data', (chunk) => {
            res.write(chunk);
        });
        proxyRes.on('end', () => {
            res.end();
        });
    });
    proxyReq.on('error', (e) => {
        console.error(`请求遇到问题: ${e.message}`);
    });

    req.on('data', (chunk) => {
        proxyReq.write(chunk);
    });
    req.on('end', () => {
        proxyReq.setHeader('Content-Type', 'text/html;charset=utf-8');
        proxyReq.end();
    });
});

server.listen(3004, () => {
    console.log('服务器正在监听3004端口');
});
相关推荐
城南vision1 小时前
计算机网络——HTTP篇
网络协议·计算机网络·http
‍。。。3 小时前
使用Rust实现http/https正向代理
http·https·rust
点点滴滴的记录12 小时前
RPC核心实现原理
网络·网络协议·rpc
程思扬14 小时前
为什么Uptime+Kuma本地部署与远程使用是网站监控新选择?
linux·服务器·网络·经验分享·后端·网络协议·1024程序员节
海绵波波10715 小时前
Webserver(4.8)UDP、广播、组播
单片机·网络协议·udp
很透彻17 小时前
【网络】传输层协议TCP(下)
网络·c++·网络协议·tcp/ip
蝌蚪代理ip19 小时前
辩论赛——动态IP与静态IP的巅峰对决
网络·网络协议·tcp/ip·ip
田三番21 小时前
使用 vscode 简单配置 ESP32 连接 Wi-Fi 每日定时发送 HTTP 和 HTTPS 请求
单片机·物联网·http·https·嵌入式·esp32·sntp
dulu~dulu21 小时前
查缺补漏----用户上网过程(HTTP,DNS与ARP)
网络·网络协议·http
丶21361 天前
【网络】HTTP(超文本传输协议)详解
网络·网络协议·http