node.js实现远程连接到外部天气数据源

//实现远程连接到外部天气数据源的HTTPWEB服务
var http = require('http');
var url = require('url');
var qstring = require('querystring');
function sendResponse(weatherData,res){
var page = '<html><head><title>External EXample</title></head>' +
'<body>' +
'<form method="post">'+
'city: <input name="city"><br>' +
'<input type="submit" value="Get Weather">'+
'</form>';
if(weatherData){
page += '<h1>Weather Info</h1><p>' +weatherData +'</p>';
}
page += '</body></html>';
res.end(page);
}
function parseWeather(weatherResponse,res){//请求处理程序读取来自api的响应
var weatherData = '';
weatherResponse.on('data',function (chunk){
weatherData += chunk;
});
weatherResponse.on('end',function(){
sendResponse(weatherData,res);//完成响应,将其返回给客户端
});
}
function getWeather(city,res){//实现对api.,,,,org的请求
var options = {
host:'api.openweathermap.org',
path:'/data/2.5/weather?q=' + city
};
http.request(options,function(weatherResponse){
parseWeather(weatherResponse,res);
}).end();
}
http.createServer(function(req,res){
console.log(req.method);

//如果方法是post,从请求流中读取表单数据
if(req.method == "post"){ 
var reqData = '';
req.on('data',function(chunk){
reqData += chunk;
});
req.on('end',function(){
var postParams = qstring.parse(reqData);//获取城市名
getWeather(postParams.city,res);
});
}else{
sendResponse(null,res);
}
}).listen(8080);
console.log('Server running at http://127.0.0.1:8080/');

posted @ 2017-01-13 14:49  jaytan  阅读(253)  评论(0编辑  收藏  举报