2011-06-25 55 views

回答

3

您訪問節點的任何其他API以同樣的方式,通過http.createClient

這個例子是基於代理,但可以適用於製作任何形式的要求

from http://www.catonmat.net/http-proxy-in-nodejs/

var http = require('http'); 

http.createServer(function(request, response) { 
    var proxy = http.createClient(80, request.headers['host']) 
    var proxy_request = proxy.request(request.method, request.url, request.headers); 

    proxy_request.addListener('response', function (proxy_response) { 
    proxy_response.addListener('data', function(chunk) { 
     response.write(chunk, 'binary'); 
    }); 
    proxy_response.addListener('end', function() { 
     response.end(); 
    }); 
    response.writeHead(proxy_response.statusCode, proxy_response.headers); 
    }); 

    request.addListener('data', function(chunk) { 
    proxy_request.write(chunk, 'binary'); 
    }); 
    request.addListener('end', function() { 
    proxy_request.end(); 
    }); 
}).listen(8080);