欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解用node.js實現(xiàn)簡單的反向代理

 更新時間:2017年06月26日 11:52:11   作者:JUN_API  
本篇文章主要介紹了詳解用node.js實現(xiàn)簡單的反向代理,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

之前用node.js實現(xiàn)簡單的反向代理,最近需要回顧,就順便發(fā)到隨筆上了

不多說直接上代碼!

const http = require('http');
const url = require('url');
const querystring = require('querystring');


http.createServer(function(oreq, ores) {
  console.log("服務(wù)已開啟");
  if (oreq) {
    if (oreq.url !== '/favicon.ico') {
      let content = '',
        postData = '';
      // 封裝獲取參數(shù)的方法
      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);
      };
      // 封裝發(fā)起http請求的方法
      function httpRequest(options, ores) {
        let datas = "";
        return http.request(options, function(res) {
          res.setEncoding('utf8');
          res.on('data', function(chunk) {
            // 返回數(shù)據(jù)
            datas += chunk;
          });
          res.on('end', function() {
            ores.writeHead(200, {
              "Content-Type": "application/json; charset = UTF-8",
              "Access-Control-Allow-Origin": "*"
            });
            ores.end(datas);
          })
        })
      };
      // 數(shù)據(jù)塊接收中
      console.log(oreq.method.toUpperCase());
      if (oreq.method.toUpperCase() === "POST") {
        console.log("進入POST");
        oreq.on("data", function(postDataChunk) {
          postData += postDataChunk;
        });
        // 數(shù)據(jù)接收完畢,執(zhí)行回調(diào)函數(shù)
        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"
          };
          // 發(fā)送請求
          let req = httpRequest(options, ores);
          req.on('error', function(e) {
            console.log('problem with request: ' + e.message);
          });
          req.write(postData); //發(fā)送請求數(shù)據(jù)
          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"
        };
        // 發(fā)送請求
        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');

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論