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

网络编程 2021-07-04 18:32www.168986.cn编程入门
本篇文章主要介绍了详解用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');

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

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by

长沙网络推广|微博营销|长沙seo优化|视频营销|长沙网络营销|微信营销|长沙网站建设|口碑营销|软文营销