问题描述
尝试通过制作一个简单的 http 代理服务器来了解有关 node.js 的更多信息.使用场景很简单:用户->代理->服务器->代理->用户
Trying to learn more about node.js by making a simple http proxy server. The use scenario is simple: user -> proxy -> server -> proxy -> user
下面的代码一直工作到最后一步.找不到将连接器的输出通过管道返回给用户的方法.
The following code works until the last step. Couldn't find way to pipe connector's output back to the user.
#!/usr/bin/env node
var
url = require('url'),
http = require('http'),
acceptor = http.createServer().listen(3128);
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);
request.pipe(connector);
request.resume();
// connector.pipe(response); // doesn't work
// connector.pipe(request); // doesn't work either
});
使用 tcpflow 我看到来自浏览器的传入请求,然后是传出代理请求,然后是服务器响应返回到代理.不知何故,我无法将响应重新传输回浏览器.
Using tcpflow I see the incoming request from the browser, then the outgoing proxy request, then the server response back to the proxy. Somehow i couldn't manage to retransmit the response back to the browser.
用管道实现这个逻辑的正确方法是什么?
What is the proper way to implement this logic with pipes?
推荐答案
你不必'暂停',只要'pipe'就可以
you dont have to 'pause', just 'pipe' is ok
var connector = http.request(options, function(res) {
res.pipe(response, {end:true});//tell 'response' end=true
});
request.pipe(connector, {end:true});
http 请求不会结束,直到你告诉它是结束";
http request will not finish until you tell it is 'end';
这篇关于通过将 http 服务器传输到 http 请求的简单 node.js 代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!