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

这篇具有很好参考价值的文章主要介绍了nodejs实现http与https服务;同时处理proxy代理的解决方案。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

// 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('服务已开启');
})

// 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('服务已开启');
})

// 正向代理 :如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('服务器关闭')
})
// 反向代理 :解决用户请求的,用户不知道
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('服务器关闭')
})
// # 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");
})
// # 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端口');
});
// # 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");
})
// # 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端口');
});

文章来源地址https://www.toymoban.com/news/detail-654567.html

到了这里,关于nodejs实现http与https服务;同时处理proxy代理的解决方案的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 超简单--搭建http、https代理服务器

    vim /etc/squid/squid.conf systemctl start squid systemctl status squid systemctl enable squid 日志位置 /var/log/squid 服务器搭建完成 linux主机配置 //编辑配置文件 vi /etc/profile //在该配置文件的最后添加代理配置 // 退出profile文件并保存 source /etc/profile // 使配置文件生效 普通PC电脑 直接在浏览器或网

    2024年02月08日
    浏览(37)
  • java使用smiley-http-proxy-servlet实现反向代理,跳过SSL认证

            nginx可以实现反向代理,但是有时候需要使用java代码来实现,经过摸索,发现有开源的项目可以实现,所以简单记录一下如何使用         没啥好说         该项目的核心类是ProxyServlet,主要操作都在这个类中实现了,我们可以继承该类,重写其中的方法,自定义

    2024年02月09日
    浏览(32)
  • nginx 开启https时反向代理http服务的问题

    当我们用nginx开启https时,反向代理一个本地的http服务,会遭遇跨域问题,报错 strict-origin-when-cross-origin ,导致很多资源无法加载。 这时只要在反向代理部分的配置文件中加入这一条语句即可:

    2024年02月14日
    浏览(27)
  • Linux服务器上配置HTTP和HTTPS代理

    本文将向你分享如何在Linux服务器上配置HTTP和HTTPS代理的方法,解决可能遇到的问题,让你的爬虫项目顺利运行,畅爬互联网! 配置HTTP代理的步骤 1. 了解HTTP代理的类型:常见的有正向代理和反向代理两种类型。根据实际需求选择不同的代理类型。 2. 安装和配置Squid代理服务

    2024年02月13日
    浏览(32)
  • squid配置http和https代理实现上网

    一、预置条件 1、一台能访问外网的内网机器作为代理服务器 2、一台无外网权限的内网机器,内网机器之间路由可达 二、实现效果 1、无外网权限机器通过代理机器实现上网 三、代理机器配置 代理机器系统centos7 1、yum install gcc openssl openssl-devel squid 安装依赖包 2、vi /etc/squ

    2024年02月09日
    浏览(28)
  • 前端开发服务器中的 Proxy 代理跨域实现原理解读

    各位朋友你们好,我是 桃小瑞 ,微信公众 @ 桃小瑞 。在这给大家拜个晚年,祝各位朋友新年快乐。 在前端的开发过程中,尤其是在浏览器环境下,跨域是个绕不开的话题,相信每个前端都会涉及到这个问题,记住的就直接手敲解决跨域问题,记不住的就只能问度娘了。😂😂

    2024年01月16日
    浏览(43)
  • Docker设置http proxy代理

    需求: 由于公司服务器无法正常访问公网,想要下载一些外部依赖包需要配置公司的内部代理。 Docker构建镜像或拉取镜像时需要通过代理访问外网,可以按照以下步骤设置HTTP代理 目录 创建目录 创建并编辑配置文件 重新加载Docker服务配置 重启Docker服务 检验是否加载配置

    2024年02月12日
    浏览(37)
  • java http请求设置代理 Proxy

    有如下一种需求,原本A要给C发送请求,但是因为网络原因,需要借助B才能实现,所以由原本的A-C变成了A-B-C。 这种情况,更多的见于内网请求由统一的网关做代理然后转发出去,比如你本地的机器想要对外上网,都是通过运营商给的出口IP也就是公网地址实现的。这种做法

    2024年02月11日
    浏览(44)
  • docker如何设置http proxy代理

    如果您使用Docker构建镜像或拉取镜像时需要使用代理,可以按照以下步骤设置HTTP代理: 创建或编辑Docker服务配置文件 如果您使用systemd管理Docker服务,可以编辑该服务的配置文件 /etc/systemd/system/docker.service.d/http-proxy.conf 。如果文件不存在,可以创建该文件。或者是 docker.ser

    2024年02月11日
    浏览(39)
  • 【Nodejs】使用Nodejs搭建HTTP服务,并实现公网远程访问

    转载自内网穿透工具的文章:使用Nodejs搭建HTTP服务,并实现公网远程访问「内网穿透」 Node.js 是能够在服务器端运行 JavaScript 的开放源代码、跨平台运行环境。Node.js 由 OpenJS Foundation(原为 Node.js Foundation,已与 JS Foundation 合并)持有和维护,亦为 Linux 基金会的项目。Node.js

    2024年02月06日
    浏览(78)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包