2016-06-08 20 views
0

我正在使用NodeJS創建天氣應用程序。 我可以從天氣站點API獲取json格式的數據。但我不明白如何將它發送到應用程序。在NodeJS天氣應用程序的頁面上打印API數據(JSON)

這裏是我的代碼:

var http = require('http'); 
 

 
http.createServer (function (request, response){ 
 
    response.writeHead(200, {'Content-Type': 'text/html'}); 
 
    response.end(); 
 
}).listen(3000); 
 

 
var getUrl = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=1111111111'; 
 

 
http.get(getUrl, function(res){ 
 
    var body = ''; 
 

 
    res.on('data', function(chunk){ 
 
     body += chunk; 
 
    }); 
 

 
    res.on('end', function(){ 
 
     var response = JSON.parse(body); 
 
     console.log("Got a response: ", response.coord.lon); 
 
    }); 
 
}).on('error', function(e){ 
 
     console.log("Got an error: ", e); 
 
});

回答

0

改變你到例如工作代碼將是把裏面的「使用getURL」的的response.end()調用最簡單的方法‘onEnd’塊:

var http = require('http'); 

http.createServer (function (request, response){ 

    response.writeHead(200, {'Content-Type': 'text/html'}); 

    var getUrl = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=1111111111'; 

    http.get(getUrl, function(res){ 

     var body = ''; 

     res.on('data', function(chunk){ 
      body += chunk; 
     }); 

     res.on('end', function(){ 

      var data = JSON.parse(body); 
      console.log("Got a response: ", data.coord.lon); 

      response.end(JSON.stringify(data)); // ENDING/SENDING RESPONSE AFTER FETCHING URL IS DONE 

     }); 
    }).on('error', function(e){ 
      console.log("Got an error: ", e); 
    }); 
}).listen(3000); 

這裏的主要問題是,createServer回調將每次觸發meone試圖訪問你的網頁,你的「getUrl」邏輯超出了這個範圍,因此不會在每個請求上運行。現在它在服務器回調中,它會。如果您打算爲此代碼添加更多功能,請考慮抽象此「getUrl」功能,但仍從服務器回調中調用它。

+0

謝謝!但是你的代碼在'response.end(data)'上拋出一個錯誤:TypeError:第一個參數必須是一個字符串或緩衝區 –

+0

對不起,你只需要將「data」轉換爲一個帶有「JSON.stringify」的字符串,更新了這篇文章。但是,如果你不需要對數據或console.log做些什麼,你可以直接將「body」變量(這是一個字符串)傳遞給「response.end(body)」。 –

+0

謝謝!那是我需要的! –

0

這是在不創建服務器的情況下最簡單的方法。

var http = require('http'); 
var getUrl = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=1111111111'; 

var request = http.get(getUrl, function(response) { 
    var jsonData = ''; 
    response.on('error', function(e) { 
    console.log("Got error: " + e.message); 
    }); 
    response.setEncoding('utf8'); 
    response.on('data', function (chunk) { 
    jsonData += chunk; 
    }); 
    response.on('end', function() { 
     console.log(jsonData); 
    }); 
}); 
request.end(); 
+0

謝謝,但我需要createServer。因爲我打算在服務器端生成內容。順便說一句,我從API很容易得到JSON,但不能粘貼到我的HTML模板。 –