Created
July 16, 2013 21:24
-
-
Save dylants/6015304 to your computer and use it in GitHub Desktop.
node.js request proxy and pipe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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