欢迎来到代码驿站!

NodeJS

当前位置:首页 > 脚本语言 > NodeJS

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

时间:2022-10-10 12:51:09|栏目:NodeJS|点击:

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

上一篇:一次NodeJS内存泄漏排查的实战记录

栏    目:NodeJS

下一篇:没有了

本文标题:详解用node.js实现简单的反向代理

本文地址:http://www.codeinn.net/misctech/215942.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有