Skip to content

Instantly share code, notes, and snippets.

@dylants
Created July 16, 2013 21:24
Show Gist options
  • Save dylants/6015304 to your computer and use it in GitHub Desktop.
Save dylants/6015304 to your computer and use it in GitHub Desktop.
node.js request proxy and pipe
/**
* Sends the output from the request to the response
*
* @param {Object} req The request
* @param {Object} res The response
*/
var pipeRequest = function(req, res) {
req.on("error", function(error) {
// Here we handle errors connecting to the server in the proxy
if (error && error.code === "ECONNREFUSED") {
console.error("Server is down or unreachable");
res.send(500, "Server is unavailable");
} else {
res.send(500, "Unknown error");
}
});
req.pipe(res);
};
/**
* Proxy's a GET request to the proxy URL, built from the proxyServer
* and proxyPort. Then pipe's the output of the request to the response.
*
* @param {Object} req The request
* @param {Object} res The response
*/
var proxyGET = function(req, res) {
var proxyUrl, _req;
proxyUrl = proxyServer + ':' + proxyPort + req.path;
_req = request.get(proxyUrl);
pipeRequest(_req, res);
};
/**
* Proxy's a POST request to the proxy URL, built from the proxyServer
* and proxyPort. Then pipe's the output of the request to the response.
*
* @param {Object} req The request
* @param {Object} res The response
*/
var proxyPOST = function(req, res) {
var proxyUrl, defaultRequest, _req;
proxyUrl = proxyServer + ':' + proxyPort + req.path;
defaultRequest = request.defaults({
json: true,
headers: {
"Content-Type":"application/json"
},
body: req.body
});
_req = defaultRequest.post(proxyUrl);
pipeRequest(_req, res);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment