javascript 如何将https函数中lat和lon的值替换为wURL(常量)?

ar5n3qh5  于 2022-11-20  发布在  Java
关注(0)|答案(1)|浏览(112)

我尝试使用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");
})
k10s72fa

k10s72fa1#

您的程式码有几个问题:

  • latlon已知之前,您过早地定义了wURL
  • response.on('data', ...)只处理HTTP响应的第一个块。如果响应很大,则可能有多个响应。请将它们全部连接起来,然后在response.on('end', ...)中处理连接。
  • 只有在完全处理了来自gURL请求的响应之后,才能向wURL发出请求。
https.get(gURL, function(response) {
  var allData = "";
  response.on('data', function(data) {
    allData += data.toString();
  }).on('end', function() {
    const city = JSON.parse(allData);
    const lat = city[0].lat;
    const lon = city[0].lon;
    const wURL = "https://api.openweathermap.org/data/2.5/weather?lat=" + lat +
      "&lon=" + lon + "&appid=" + apiKey + "&units=" + units;
    https.get(wURL, function(response) {
      var allData = "";
      response.on('data', function(data) {
        allData += data.toString();
      }).on('end', function() {
        const climate = JSON.parse(allData);
        ...
        res.send();
      });
    });
  });
});

相关问题