I got this code for a weather app that I am building in NodeJS. when I receive the response from the nodejs I receive the details(temperature, rain) in plain text. So I cannot style it. is there any method I can use to get the response as a styled site with CSS? I cannot use a prebuilt html code cause the weather is always changing. Is there a mthod to get a styled site?
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")
}
});
});
});
CodePudding user response:
Here are some of the options you have:
Your API can fetch JSON data (no HTML) and then you programmatically insert that into your page with Javascript in the web page by inserting that data into the already styled page to replace the data that is already there. This should then inherit the styling that you already have, using the existing CSS rules. If you have a client-side template system such as EJS, you could use that to generate HTML from a template stored in your page with the new data inserted into the template and then insert that generated HTML into the page. Or, you can insert the data manually into the existing HTML with your own Javascript.
Your API can fetch a piece of styled HTML that uses CSS classes and ids that will inherit the existing CSS rules already in the page. You then use client-side Javascript to insert this piece of styled HTML into your existing page and it will automatically be able to use the CSS rules already in the page.
Your API can fetch a whole new HTML body which can then insert. You can either include CSS rules in the new HTML body or you can use the existing CSS rules from the page.
CodePudding user response:
Hi @Pasindu sathsara,
My understanding - you are asking for a css style change respective to response( correct me if i am deviated)
The idea is like,
- Understand the api response.
- Write N number of style tag w.r.t climate and keep it as node string
- Have a simple switch and compare climate and get the climate
- According to climate res.write(css style tag in variable ) before res.end() so that style is dynamic according to response
Regards,
Muhamed