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端口');
});
相关推荐
C++忠实粉丝2 小时前
计算机网络socket编程(3)_UDP网络编程实现简单聊天室
linux·网络·c++·网络协议·计算机网络·udp
Gworg2 小时前
创建HTTPS网站
安全·https·ssl
C++忠实粉丝4 小时前
计算机网络socket编程(4)_TCP socket API 详解
网络·数据结构·c++·网络协议·tcp/ip·计算机网络·算法
Estar.Lee4 小时前
时间操作[取当前北京时间]免费API接口教程
android·网络·后端·网络协议·tcp/ip
蝶开三月4 小时前
php:使用socket函数创建WebSocket服务
网络·websocket·网络协议·php·socket
G丶AEOM4 小时前
SSL/TLS,SSL,TLS分别是什么
网络·网络协议·网络安全
木子_lishk5 小时前
gateway 支持同时使用 https 和 http访问
https·gateway
Koi慢热5 小时前
路由基础(全)
linux·网络·网络协议·安全
刽子手发艺7 小时前
WebSocket详解、WebSocket入门案例
网络·websocket·网络协议