我如何用CSS样式NodeJS响应?



我得到了我在NodeJS中构建的天气应用程序的代码。当我收到来自nodejs的响应时,我收到纯文本的详细信息(温度,雨)。所以我不能设置样式。有什么方法,我可以使用得到响应与CSS风格的网站?我不能使用预构建的html代码,因为天气总是在变化。是否有一种方法来获得一个风格的网站?

app.post('/', function(req,res){
const query=req.body.cityName;
const apiKey=' '
const url="https://api.openweathermap.org/data/2.5/weather?units=metric&q="+query+"&appid="+apiKey;
https.get(url,function(response){
console.log(response.statusCode);
response.on("data",function(data){
const weatherData = JSON.parse(data);
console.log(weatherData);
try{
const temp = weatherData.main.temp;
console.log(temp);
const weatherWescription = weatherData.weather[0].description;
console.log(weatherWescription)
const icon =weatherData.weather[0].icon;
const iconUrl="http://openweathermap.org/img/wn/"+icon+"@2x.png"

res.write("<h1> The Weather is currently " + weatherWescription + "</h1>");
res.write("<h1> Temperature is "+temp+"</h1>");
res.write("<img src="+iconUrl+">")

res.send();
}
catch(e){
res.send("Enter a Valid City Name")
}

});
});

});

以下是一些您可以选择的选项:

  1. 您的API可以获取JSON数据(没有HTML),然后您通过将该数据插入到已经有样式的页面中,以编程方式将其插入到网页中的Javascript页面中,以取代已经存在的数据。然后,它应该使用现有的CSS规则继承您已经拥有的样式。如果有EJS这样的客户端模板系统,可以使用它从存储在页面中的模板生成HTML,将新数据插入到模板中,然后将生成的HTML插入到页面中。或者,您可以使用自己的Javascript将数据手动插入到现有的HTML中。

  2. 你的API可以获取一段样式化的HTML,它使用CSS类和id来继承页面中已经存在的CSS规则。然后使用客户端Javascript将这段样式化的HTML插入到现有页面中,它将自动能够使用页面中已经存在的CSS规则。

  3. 你的API可以获取一个全新的HTML主体,然后插入。你可以在新的HTML正文中包含CSS规则,也可以使用页面中已有的CSS规则。

嗨@Pasindu sathsara,
我的理解-你是要求css样式改变各自的响应(如果我偏离了请纠正我)

意思是,

  1. 了解api响应
  2. 写入N个样式标签w.r.t climate,并保留为节点字符串
  3. 有一个简单的开关和比较气候,得到气候
  4. 根据气候res.write(css style tag in variable)在res.end()之前,使样式是动态的,根据响应

问候,
muhame

最新更新