当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 详解用node.js实现简单的反向代理

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

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

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网