Skip to content

Instantly share code, notes, and snippets.

@AdmiralPotato
Created February 13, 2013 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdmiralPotato/4949433 to your computer and use it in GitHub Desktop.
Save AdmiralPotato/4949433 to your computer and use it in GitHub Desktop.
How to get a JSON response from an external server and serve it back as the response to an HTTP request
var http = require('http');
var clientResponseDataHandler = function(chunk) {
this.compiledResponseString += chunk;
}
var clientResponseEndHandler = function() {
var propertyName, httpResponse;
console.log('-----------------------------------------------------------');
console.log('END OF DATA FROM REMOTE SERVER');
for (propertyName in this) {
if (this.hasOwnProperty(propertyName)) {
console.log(propertyName);
}
}
console.log('complete: ', this.complete);
console.log('req: ', this.req);
httpResponse = this.req.theOriginalHttpResponseThatNeedsToBePassedThroughThisChainOfEvents;
httpResponse.writeHead(200,{'Content-Type':'text/plain'});
httpResponse.end(this.compiledResponseString);
};
var clientResponseHandler = function(clientResponse) {
//console.log(clientResponse);
clientResponse.compiledResponseString = '';
console.log('STATUS: ' + clientResponse.statusCode);
console.log('HEADERS: ' + JSON.stringify(clientResponse.headers));
clientResponse.setEncoding('utf8');
clientResponse.on('data', clientResponseDataHandler);
clientResponse.on('end', clientResponseEndHandler);
};
var clientRequestErrorHandler = function(error) {
console.log('problem with request: ', error);
};
var serverRequestHandler = function(serverRequest, serverResponse) {
if(serverRequest.url !== '/favicon.ico'){
var remoteAddress = 'http://vimeo.com/api/v2/admiral/likes.json';
var clientRequest = http.request(remoteAddress, clientResponseHandler);
clientRequest.theOriginalHttpResponseThatNeedsToBePassedThroughThisChainOfEvents = serverResponse;
console.log('-----------------------------------------------------------');
console.log('Firing request to: ', remoteAddress);
console.log('-----------------------------------------------------------');
clientRequest.on('error', clientRequestErrorHandler);
//clientRequest.parser.on('body', clientRequestParserBodyHandler);
clientRequest.end();
}
};
var server = http.createServer(serverRequestHandler);
server.listen(9001);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment