我尝试使用express.js和node.js来制作这个天气网页应用程序时,遇到了一个问题。我想使用https函数中生成的'lat'和'lon'值到wURL中(我在那里存储了获取天气数据的url。这个url只接受纬度和经度)。所以,有人能帮我找到解决方案吗?
先谢谢你。
const express = require('express');
const https = require('node:https');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/', function(req, res) {
res.sendFile(\__dirname + "/index.html");
});
app.post('/', function(req, res) {
const query = req.body.cityName;
const apiKey = "904f8e391a422fdf63b802aef88950c8";
const units = "metric";
//for lat long
const gURL = "https://api.openweathermap.org/geo/1.0/direct?q=" + query + "&limit=2&appid=" + apiKey;
//for weather
const wURL = "https://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&appid=" + apiKey + "&units=" + units;
https.get(gURL, function(response) {
response.on('data', function(data) {
const city = JSON.parse(data);
const lat = city\[0\].lat;
const lon = city\[0\].lon;
});
});
https.get(wURL, function(response) {
response.on('data', function(data) {
const climate = JSON.parse(data);
const temp = climate.main.temp;
const location = climate.name;
const description = climate.weather\[0\].description;
const icon = climate.weather\[0\].icon;
const imgURL = 'http://openweathermap.org/img/wn/' + icon + '@2x.png';
res.write('\<h1\>The temperature in ' + location + ' is ' + temp + ' degC.\</h1\>');
res.write('\<p\>The weather is currently ' + description + '\</p\>');
res.write("\<img src=" + imgURL + "\>");
res.send();
})
})
});
app.listen(3000, function() {
console.log("Server is running on port:3000");
})
1条答案
按热度按时间k10s72fa1#
您的程式码有几个问题:
lat
和lon
已知之前,您过早地定义了wURL
。response.on('data', ...)
只处理HTTP响应的第一个块。如果响应很大,则可能有多个响应。请将它们全部连接起来,然后在response.on('end', ...)
中处理连接。gURL
请求的响应之后,才能向wURL
发出请求。