如何在 express.js 中使用 response.send () 发送的数据样式



我想在 app.post(( 方法中设置我发回的数据的样式。我怎样才能做到这一点?

这是 app.post(( 代码:

app.post("/",function(req,res){
const query = req.body.cityName;
const cityName = query.charAt(0).toUpperCase() + query.slice(1);
const apiKey = "fc2f5f2ba2fe9d109d021ef0f57ef03d";
const unit ="metric";
const url = "https://api.openweathermap.org/data/2.5/weather?q=" + cityName + "&appid=" + apiKey + "&units=" + unit;
https.get(url,function(response){
console.log(response.statusCode);
response.on('data', function(data){
const weatherData = JSON.parse(data);
const temp = weatherData.main.temp;
const weatherDescription = weatherData.weather[0].description;
const icon = weatherData.weather[0].icon;
const imageURL = "http://openweathermap.org/img/wn/" + icon + "@2x.png";
res.write("<h1>The temperature in " + cityName + " is " + temp + " degrees Celcius</h1>");
res.write("<h3>The weather is currently " + weatherDescription + "</h3>");
res.write("<img src="+ imageURL +">");
res.send();
})
});
})

模板文字可以实现您的目标.
您也可以选择使用图像标签并将其插入反勾号之间。 您应该没有问题,因为我已经使用虚拟变量对其进行了测试。

res.send(
`<h1>The temperature in ${cityName} is ${temp} degrees Celcius</h1>
<h3 style="background-image: url('${imageURL}')">The weather is currently ${weatherDescription} </h3>
`);

一如既往地使用内联样式。 或者,您可以使用单独的 HTML 文件在返回结果时呈现,并使用其中的结果值。 我的意思是有一个单独的HTML文件("天气.html"(,然后将数据渲染到其中。 天气.html看起来像这样:

<h1>temperature in {%CITY%} is {%temperature%}</>

我想你现在明白了。 有了事物的一些占位符,我们需要是动态值。 然后,您所要做的就是使用文件系统并读取您需要渲染的单独HTML文件,然后相应地放置数据。

const fs = require('fs');
response.on('data', function(data){
const weatherData = JSON.parse(data);
const temp = weatherData.main.temp;
const weatherDescription = weatherData.weather[0].description;
const icon = weatherData.weather[0].icon;
const imageURL = "http://openweathermap.org/img/wn/" + icon + "@2x.png";
fs.readfile(`${__dirname}/weather.html`,'utf-8',(err,data)=>{
let output = data.replace('{%CITY%}', data.city)
})

它看起来像那样。试试吧。

最新更新