//由于蓝奏云有限制,不能直接上传*.js 文件,所以需要将proxy.txt 文件重命名proxy.js 即可 //自定义配置-----开始---- var listenHost = '0.0.0.0';//监听地址不用改 var port = '80';//监听端口,与tiny配置端口一致 var realHostName="test";//自定义请求主机名 var headerKey = "abc";//随便赋值,但要与tiny配置一致【防盗验证】 //自定义配置-----结束---- var net = require('net') var url = require('url') var http = require('http') //=================================== // 这个服务从请求报文中解析出请求 URL 和其他必要参数,新建到服务端的请求, // 并把代理收到的请求转发给新建的请求,最后再把服务端响应返回给浏览器。 // =================================== var request = (creq,cres)=>{ try{ console.log() console.log() var realHost = creq.headers[realHostName] || creq.headers.host || creq.headers.Host; var mapUrl = creq.url; //console.log("http",creq.headers) //console.log("creq.headers.headerKey:"+creq.headers["headerKey"]+";headerKey:"+headerKey); //防盗验证 if(headerKey && creq.headers["headerkey"] != headerKey){ realHost="127.0.0.1:12345" } if(realHost){ if(creq.url.indexOf("http")==0){//http开头,标准圣子代理 mapUrl=creq.url.replace(/http:\/\/[^/]+/,`http://${realHost}`); }else{ mapUrl=`http://${realHost}${creq.url}`; } creq.headers.host = realHost; } console.log("http请求的url:",mapUrl); var u = url.parse(mapUrl); // =============== // 重新构建请求 // =============== var options = { hostname : realHost, port : u.port || 80, path : u.path, method : creq.method, headers : creq.headers, }; // ================== // 得到响应 // ================== var preq = http.request(options, (pres)=>{ cres.writeHead(pres.statusCode,pres.headers);//估计是添加头 pres.pipe(cres);//装入 }).on('error',function(e){ console.error("http.error",e) cres.end(); }); creq.pipe(preq); }catch(e){ console.error("http.error.catch",e) } } // ================================== // 这个服务从 CONNECT 请求报文中解析出域名和端口, // 创建到服务端的 TCP 连接,并和 CONNECT 请求中的 TCP 连接串起来, // 最后再响应一个 Connection Established 响应。 // =============================== var connect = (creq, csock) =>{ try{ console.log() console.log() var realHost = creq.headers[realHostName] || creq.headers.host || creq.headers.Host; var mapUrl = "http://"+creq.url; // console.log("https.headers",creq.headers) // console.log("creq.headers.headerKey:"+creq.headers["headerKey"]+";headerKey:"+headerKey); //防盗验证 if(headerKey && creq.headers["headerkey"] != headerKey){ realHost="127.0.0.1:12345" } if(realHost){ mapUrl=`http://${realHost}`; creq.headers.host = realHost; } console.log("http.connect请求的url:",mapUrl); var u = url.parse(mapUrl); var psock = net.connect(u.port, u.hostname, ()=>{ csock.write('HTTP/1.1 200 Connection Established'); psock.pipe(csock); }) .on('error',(e)=>{ console.error("http.connect",e) csock.end(); }); csock.pipe(psock); csock.on('error',(err)=>{ console.error("socket.err",err); }); }catch(e){ console.log("http.connect.catch",e) } } var proxy = http.createServer() .on('request',request) .on('connect',connect); proxy.listen(port, listenHost,() =>{ console.log(`Proxy run in ${listenHost}:${port}`); }) .setTimeout(0)