Hello I am trying to post 4 key values (weatherDescription, query, temp, imageURL) to a success.ejs file. But these values are within an if statement. Currently they are just sent to a blank HTML doc and i want to CSS the success page. Any tips to accomplish this would be very appreciated!
app.post("/", function(req, res){
const query = req.body.cityName;
const unit = "metric";
const apiKey = "********";
const url = "https://api.openweathermap.org/data/2.5/weather?appid=" +
apiKey + "&q=" + query + "&units=" + unit;
https.get(url, function(response){
console.log(response.statusCode);
if (response.statusCode === 200) {
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("<p>The weather is currently " + weatherDescription + "
</p>");
res.write("<h1>The temperature in " + query + " is " + temp + "
degrees Celcius.</h1>");
res.write("<img src=" + imageURL + ">");
res.send();
});
} else {
res.sendFile(__dirname + "/failure.html");
}
});
});
app.post("/success", function(req, res){
res.redirect("/success");
});
app.post("/failure", function(req, res) {
res.redirect("/");
});
In success.ejs:
<p><%= weatherDescription %></p>
<p><%= query %></p>
<p><%= temp %></p>
<p><%= imageURL %></p>
You're able to easily send content to an EJS file using res.render's parameters. For example, you can call res.render with these parameters:
res.render( path.join(__dirname, "success.ejs"), { weatherDescription : weatherDescription, query : query, temp : temp, imageURL : imageURL } );
And access them from EJS through:
<p>The weather is currently <%= weatherDescription %></p>
<h1>The temperature in <%= query %> is <%= temp %> degrees Celcius.</h1>
<img src="<%= imageURL %>">
If this helped, mark it as an answer. (it probably didnt)