Reputation: 183
Can some one explain this code to create a proxy server. Everything makes sense except the last block. request.pipe(proxy - I don't get that because when proxy is declared it makes a request and pipes its response to the clients response. What am I missing here? Why would we need to pipe the original request to the proxy because the http.request method already makes the request contained in the options var.
var http = require('http');
function onRequest(request, response) {
console.log('serve: ' + request.url);
var options = {
hostname: 'www.google.com',
port: 80,
path: request.url,
method: 'GET'
};
var proxy = http.request(options, function (res) {
res.pipe(response, {
end: true
});
});
request.pipe(proxy, {
end: true
});
}
http.createServer(onRequest).listen(8888);
Upvotes: 8
Views: 16757
Reputation: 123423
What am I missing here? [...] the http.request method already makes the request contained in the options var.
http.request()
doesn't actually send the request in its entirety immediately:
[...] With
http.request()
one must always callreq.end()
to signify that you're done with the request - even if there is no data being written to the request body.
The http.ClientRequest
it creates is left open so that body content, such as JSON data, can be written and sent to the responding server:
var req = http.request(options);
req.write(JSON.stringify({
// ...
}));
req.end();
.pipe()
is just one option for this, when you have a readable stream, as it will .end()
the client request by default.
Although, since GET
requests rarely have a body that would need to be piped or written, you can typically use http.get()
instead, which calls .end()
itself:
Since most requests are GET requests without bodies, Node provides this convenience method. The only difference between this method and
http.request()
is that it sets the method to GET and callsreq.end()
automatically.
http.get(options, function (res) {
res.pipe(response, {
end: true
});
});
Upvotes: 9
Reputation: 3241
Short answer: the event loop. I don't want to talk too far out of my ass, and this is where node.js gets both beautiful and complicated, but the request isn't strictly MADE on the line declaring proxy: it's added to the event loop. So when you connect the pipe, everything works as it should, piping from the incoming request > proxy > outgoing response. It's the magic / confusion of asynchronous code!
Upvotes: 1