问题描述
尝试通过制作简单的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?
推荐答案
好的。明白了。
更新:NB!正如评论中所报告的那样,此示例不再起作用。很可能是由于Streams2 API更改(节点0.9 +)
UPDATE: NB! As reported in the comments, this example doesn't work anymore. Most probably due to the Streams2 API change (node 0.9+)
管道返回客户端必须在连接器的回调中发生,如下所示:
Piping back to the client has to happen inside connector's callback as follows:
#!/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, function(serverResponse) {
serverResponse.pause();
response.writeHeader(serverResponse.statusCode, serverResponse.headers);
serverResponse.pipe(response);
serverResponse.resume();
});
request.pipe(connector);
request.resume();
});
这篇关于简单的node.js代理通过将http服务器传递给http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!