之前用node.js實現簡單的反向代理,最近需要回顧,就順便發到隨筆上了
不多說直接上代碼!
const http = require('http');const url = require('url');const querystring = require('querystring');http.createServer(function(oreq, ores) { console.log("服務已開啟"); if (oreq) { if (oreq.url !== '/favicon.ico') { let content = '', postData = ''; // 封裝獲取參數的方法 function getParmas(oUrl) { let oQuery = (typeof oUrl === "object") ? oUrl : url.parse(oUrl, true).query, data = {}; for (item in oQuery) { if (item !== 'hostname') { if (item !== 'path') { data[item] = oQuery[item]; } } } return querystring.stringify(data); }; // 封裝發起http請求的方法 function httpRequest(options, ores) { let datas = ""; return http.request(options, function(res) { res.setEncoding('utf8'); res.on('data', function(chunk) { // 返回數據 datas += chunk; }); res.on('end', function() { ores.writeHead(200, { "Content-Type": "application/json; charset = UTF-8", "Access-Control-Allow-Origin": "*" }); ores.end(datas); }) }) }; // 數據塊接收中 console.log(oreq.method.toUpperCase()); if (oreq.method.toUpperCase() === "POST") { console.log("進入POST"); oreq.on("data", function(postDataChunk) { postData += postDataChunk; }); // 數據接收完畢,執行回調函數 oreq.on("end", function() { console.log("接收完畢") console.log(postData); // 配置options let oData = JSON.parse(postData); postData = getParmas(oData); let options = { hostname: oData.hostname, port: '80', path: oData.path, method: "POST" }; // 發送請求 let req = httpRequest(options, ores); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); req.write(postData); //發送請求數據 req.end(); }); } else { let queryObj = url.parse(oreq.url, true).query; content = getParmas(oreq.url); let options = { hostname: queryObj.hostname, port: '80', path: queryObj.path + content, method: "GET" }; // 發送請求 let req = httpRequest(options, ores); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); req.end(); } } }}).listen(8080, '127.0.0.1');以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答