Listing 29.9 implements the backend web service on the Node.js server. The service exports the getWeather()
route handler to handle the /weather
route in Express. When this code receives the request, it pulls the city name from req.query.city
and uses it to make the remote web request on the server. The parseWeather()
function handles the request.
The parseWeather()
function reads the data and formats it into a JavaScript object that the client can more easily consume. res.json()
returns the results.
01 var http = require('http'),
02 function toFahrenheit(temp){
03 return Math.round((temp-273.15)*9/5+32);
04 }
05 function parseWeather(req, res, weatherResponse) {
06 var weatherData = '';
07 weatherResponse.on('data', function (chunk) {
08 weatherData += chunk;
09 });
10 weatherResponse.on('end', function () {
11 var wObj = JSON.parse(weatherData);
12 if (wObj.name){
13 var wData = {
14 name: wObj.name,
15 temp: toFahrenheit(wObj.main.temp),
16 tempMin: toFahrenheit(wObj.main.temp_min),
17 tempMax: toFahrenheit(wObj.main.temp_max),
18 humidity: wObj.main.humidity,
19 wind: Math.round(wObj.wind.speed*2.23694), //mph
20 clouds: wObj.clouds.all,
21 description: wObj.weather[0].main,
22 icon: wObj.weather[0].icon
23 };
24 } else {
25 wObj = {name: "Not Found"};
26 }
27 res.json(wData);
28 });
29 }
30 exports.getWeather = function(req, res){
31 var city = req.query.city;
32 var options = {
33 host: 'api.openweathermap.org',
34 path: '/data/2.5/weather?q=' + city
35 };
36 http.request(options, function(weatherResponse){
37 parseWeather(req, res, weatherResponse);
38 }).end();
39 }