node.js 制作简单的ProxyServer

博客首页 » node.js 制作简单的ProxyServer

发布于 22 Jun 2014 15:21
标签 blog
Node.js为我们带来简洁强大的异步方式的程序。这次我们写一个简单的ProxyServer。

#!/usr/bin/env node
 
var
    url = require('url'),
    http = require('http'),
    acceptor = http.createServer().listen(8000);
 
acceptor.on('request', function(request, response) {
    console.log('request ' + request.url);
    request.pause();
    var options = url.parse(request.url);
    options.headers = request.headers;
    options.method = request.method;
    options.agent = false;
 
    var connector = http.request(options, function(serverResponse) {
            serverResponse.pause();
            response.writeHeader(serverResponse.statusCode, serverResponse.headers);
            serverResponse.pipe(response);
            serverResponse.resume();
    });
 
    connector.on('error', function (exc) {
        console.log('ignoring exception' + exc);
    });
 
    request.pipe(connector);
    request.resume();
});
 
acceptor.on('error', function (exc) {
    sys.log('ignoring exception' + exc);
});

Reference:

http://stackoverflow.com/questions/13472024/simple-node-js-proxy-by-piping-http-server-to-http-request

http://stackoverflow.com/questions/20351637/how-to-create-a-simple-http-proxy-in-node-js


本页面的文字允许在知识共享 署名-相同方式共享 3.0协议和GNU自由文档许可证下修改和再使用,仅有一个特殊要求,请用链接方式注明文章引用出处及作者。请协助维护作者合法权益。


系列文章

文章列表

  • node.js 制作简单的ProxyServer

这篇文章对你有帮助吗,投个票吧?

rating: 0+x

留下你的评论

Add a New Comment
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License