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端口');
});
相关推荐
打鱼又晒网1 小时前
linux网络套接字 | 深度解析守护进程 | 实现tcp服务守护进程化
linux·网络协议·计算机网络·tcp
青灯文案11 小时前
前端 HTTP 请求由 Nginx 反向代理和 API 网关到后端服务的流程
前端·nginx·http
小林熬夜学编程3 小时前
【Linux网络编程】第十四弹---构建功能丰富的HTTP服务器:从状态码处理到服务函数扩展
linux·运维·服务器·c语言·网络·c++·http
njnu@liyong14 小时前
图解HTTP-HTTP报文
网络协议·计算机网络·http
ZachOn1y14 小时前
计算机网络:应用层 —— 应用层概述
计算机网络·http·https·应用层·dns
kaixin_learn_qt_ing15 小时前
了解RPC
网络·网络协议·rpc
爱吃水果蝙蝠汤17 小时前
DATACOM-IP单播路由(BGP)-复习-实验
网络·网络协议·tcp/ip
网安墨雨21 小时前
iOS应用网络安全之HTTPS
web安全·ios·https
言成言成啊1 天前
TCP与UDP的端口连通性
网络协议·tcp/ip·udp
敲代码娶不了六花1 天前
对计算机网络中“层”的理解
网络·网络协议·tcp/ip·计算机网络