我正在使用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);
});
謝謝!但是你的代碼在'response.end(data)'上拋出一個錯誤:TypeError:第一個參數必須是一個字符串或緩衝區 –
對不起,你只需要將「data」轉換爲一個帶有「JSON.stringify」的字符串,更新了這篇文章。但是,如果你不需要對數據或console.log做些什麼,你可以直接將「body」變量(這是一個字符串)傳遞給「response.end(body)」。 –
謝謝!那是我需要的! –