繁体   English   中英

如何在 node.js (openweathermap.api) 中呈现 html 格式

[英]how to render html format in node.js (openweathermap.api)

这是我下面的代码。 我想做的是在渲染时,我想将 html 格式渲染到 index.pug 而不使用 res.send(body); 当我输入邮政编码时,index.pug 中的文本下方将显示类似以下链接的结果。

身体是这个链接。 此链接是在 html 中设计的,而不是图像。

我想使用的链接

主题.js

 router.post('/weather', function(req,res){
      let url = `http://api.openweathermap.org/data/2.5/weather?zip=${req.body.zipcode}&mode=html&units=imperial&appid=${apiKey}`
      request(url, function (err, response, body) {
//this below code works but not what I wanna do           
res.send(body);
//this is something I'd like to use
res.render('index',text:body);
          }
       });
    })

索引.pug

h1= text

您看到的第一个问题是调用 OpenWeather API 并且一次只获取一个邮政编码。 让我们先解决这个问题,然后我们需要解决将数据有效地放入 pug 模板中的问题,您可以在其中生成表。

1. 获取多个值

API 规范说您可以将多个城市 ID串在一起,但不能将邮政编码串在一起。 如果您想在路线中保持轻松,您应该切换到城市 ID:

http://api.openweathermap.org/data/2.5/group?id=524901,703448,2643743&units=metric

否则,您将需要多次调用路由中的 api,使用诸如async 之类的库是可能的,但您说您刚刚开始编程,所以这可能不是一个好的第一步。

希望您的应用程序可以使用城市 ID,或者至少您可以从它开始。

2. 将结果发送到模板

多城市查询的结果如下所示

{"cnt":3,"list":[{"coord":{"lon":37.62,"lat":55.75},"sys":{"type":1,"id":7323,"message":0.0036,"country":"RU","sunrise":1485753940,"sunset":1485784855},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"main":{"temp":-10.5,"pressure":1028,"humidity":66,"temp_min":-11,"temp_max":-10},"visibility":10000,"wind":{"speed":5,"deg":200},"clouds":{"all":0},"dt":1485793175,"id":524901,"name":"Moscow"},{"coord":{"lon":30.52,"lat":50.45},"sys":{"type":1,"id":7358,"message":0.0268,"country":"UA","sunrise":1485754480,"sunset":1485787716},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"main":{"temp":-11.04,"pressure":1033,"humidity":61,"temp_min":-15,"temp_max":-9},"visibility":10000,"wind":{"speed":3,"deg":150},"clouds":{"all":0},"dt":1485793175,"id":703448,"name":"Kiev"},{"coord":{"lon":-0.13,"lat":51.51},"sys":{"type":1,"id":5091,"message":0.0034,"country":"GB","sunrise":1485762036,"sunset":1485794875},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50d"},{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"main":{"temp":7,"pressure":1012,"humidity":81,"temp_min":5,"temp_max":8},"visibility":10000,"wind":{"speed":4.6,"deg":90},"clouds":{"all":90},"dt":1485793175,"id":2643743,"name":"London"}]}

您需要遍历list属性中的每个实体并提取所需的数据。 这是一个使用for...of的示例,它遍历结果,为每个城市创建一个新的更简单的对象,然后将其添加到 weatherData 数组中。 只需使用 res.render 将 weatherData 传递到您的模板中,您就会发现创建表格非常容易。

var weatherData = [];

for(var city in body.list){
  var cityWeather = {
    "name": city.name,
    "temperature": city.main.temp,
    "weather": city.weather[0].description
  };

  weatherData.push(cityWeather);

}

res.render('topic/weather', {"cities": weatherData});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM