栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

详解用node.js实现简单的反向代理

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

详解用node.js实现简单的反向代理

之前用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');

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/86785.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号