Monday, March 19, 2012

node.js http request example

A http server acting as a google reverse geocoder API proxy.

You just need to pass in long/lat as querystrings, for example, "localhost/?hi=there&long=37&lat=37". I put the hi=there in there because node querystring module parses strangely...

var http = require('http'),
q = require('querystring')
http.createServer(function (req, res) {
//create the geo long/lat path
var url=["/maps/geo?q="
,q.parse(req.url)["long"]
,","
,q.parse(req.url)["lat"]
,"&output=json&sensor=false"].join(""),
//create the options to pass into the get request
options={host:"maps.google.com"
,path:url};
//a little lightweight logging to watch requests
console.log("url:",options.host+options.path);
console.log("requrl:",req.url);
//make the request server side
http.get(options,function(response){
//console.log("hi",response);
res.writeHead(200, {'Content-Type': 'text/plain'});
var pageData = "";
response.setEncoding('utf8');
//stream the data into the response
response.on('data', function (chunk) {
pageData += chunk;
});
//write the data at the end
response.on('end', function(){
res.write(pageData);
res.end();
});
});
}).listen(80);
view raw server.js hosted with ❤ by GitHub