How can I style the data sent using response.send () in express.js

Viewed 571

I want to style the data I send back in the app.post() method. How can I achieve that?

This is the app.post() code:

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();
    })

  });
})
2 Answers

Using inline styles would be an option as always. Or you can use a separate HTML file to render when the results come back and use the resulting values in it. what I am saying is having a separate HTML file ('weather.html') and then render the data into it. weather.html would look something like this:

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

I think you get the idea now. with some placeholders for the things, we need to be dynamic values. Then all you have to do is to use file system and read the separate HTML file you need to render and then put the data accordingly.

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)
})

it would look something like that. Try it.

Template literals could achieve your goal.
You could opt to use an image tag as well and insert that between the back ticks. You should have no issues since I've tested it using dummy variables.

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

Related