1. 程式人生 > >node 實現代理服務

node 實現代理服務

var http=require("http");
var url=require("url");
var server=http.createServer(function(sreq,sres){
    var url_parts=url.parse(sreq.url);
    var opts={
        host:"www.taobao.cn",
        port:80,
        path:url_parts.pathname,
        headers:sreq.headers
    };
    var creq=http.get(opts, function (cres) {
        sres.writeHead(cres.statusCode,cres.headers);
        cres.pipe(sres);
    });
    sreq.pipe(creq);
});
server.listen(1337,"127.0.0.1", function () {
    console.log("開始監聽"+server.address().port+"......");
});

2.

var http = require('http')
var request = require('request')

var server = http.createServer(onRequest).listen(3000)

function onRequest (req, res) {
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080')
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE')
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type')
  res.setHeader('Access-Control-Allow-Credentials', true)

  req.url = 'http://www.taobao.com' + req.url

  console.log(`SUCCESS CONNECT   ${req.url}`)
  if (req.method === 'GET') {
    if (req.url) {
      // request方法返回的物件兼具可讀和可寫許可權,所以可以直接通過pipe給客戶端返回值
      request({
        url: req.url
      }).on('error', function (e) {
        res.end(e)
      }).pipe(res)
    } else {
      res.end('no url found')
    }
  } else if (req.method === 'POST') {
    if (req.url) {
      let body = ""
      req.on('data', function (chunk) {
        body += chunk;
      })
      req.on('end', function () {
        // 這裡的 from 其實就是把 data 組裝成自己想要的格式
        let data = body.split('=')
        request.post(req.url).form({body:data[1]}).on('error', e => res.end(e)).pipe(res)
      })
    } else {
      res.end('wrong post')
    }
  } else {
    res.end('wrong method')
  }

}

3.

var http = require("http");
var server = http.createServer(function(req, res) {
  var opts = {
    host: '115.239.210.27',
    port: '80',
    path: req.url,
    method: req.method,
    headers: req.headers
  };
	console.log(req.httpVersion);//描述HTTP協議版本,通常是1.0或者1.1
    console.log(req.headers);//描述HTTP請求頭
    console.log(req.method);//描述HTTP請求方法,比如GET,POST,PUT,DELETE等
    console.log(req.url);//原始的請求路徑
    console.log(req.trailers);//HTTP請求尾
    console.log(req.complete);//描述這個請求資訊是不是傳送完成了
  // 如果後端服務需要check host頭的話,代理請求頭就不能直接透明代理了
   req.headers["host"] = opts.port ? (opts.host+":"+opts.port) : (opts.host)
  var proxy = http.request(opts, function(resProxy) {
    res.writeHead(resProxy.statusCode, resProxy.headers);//向請求的客戶端傳送響應頭
	/////
	var _data = '';
    //resProxy.setEncoding('binary');//編碼
    resProxy.on('data', function(data) { //響應返回資料,並接受
    _data += data;
	});
	resProxy.on('end', function() { //資料返回完畢
            // console.log(_data + '2222');
            var _SentData = new Buffer(_data, 'binary');//轉換編碼
            //console.log(Buffer);
            });
	/////
    resProxy.pipe(res);//轉發
    });
  ///////
  proxy.on('error', function(e) { //響應出錯呼叫函式
        console.log('problem with handle_get_pic: ' + e.message);
        log.log_err('handle_get_pic->>>:' + e.message);
        //callback('PicError','');
        });
  //////
  req.pipe(proxy); //轉發?
  proxy.end();
});
server.listen(8080);