I am trying to build simple weather app using node.js. I want to display weather information in the separate ejs file.
My code in post route looks like this:
app.post('/', (req, res) => {
var address = req.body.address;
location.getLocation(address, (error, results) => {
if(error) {
console.log(error);
} else {
fetchWeather.getWeather(results.latitude, results.longitude, (error,
weatherResults) => {
if(error){
console.log(error);
} else {
var temp = weatherResults.temperature;
var appTemp = weatherResults.apparentTemperature;
console.log(temp, appTemp);
}
});
}
});
res.redirect('weatherinfo');
});
I am using request to get data in seperate file :
var getWeather = (lat, lng, callback) => {
request({
url:`https://api.darksky.net/forecast/mycode/${lat},${lng}
?units=si`,
json: true
}, (error, response, body) => {
if (!error && response.statusCode === 200) {
callback(undefined, {
temperature: body.currently.temperature,
apparentTemperature: body.currently.apparentTemperature
});
} else {
callback('Unable to fetch weather.');
}
});
};
How can I export temperature and apparentTemperature to my ejs file?
You can pass the temperature data to the view as variables:
app.post('/', (req, res) => {
var address = req.body.address;
location.getLocation(address, (error, results) => {
if(error) {
console.log(error);
} else {
fetchWeather.getWeather(results.latitude, results.longitude, (error, weatherResults) => {
if(error){
console.log(error);
} else {
var temp = weatherResults.temperature;
var appTemp = weatherResults.apparentTemperature;
res.render('pages/yourFile.ejs, {
temp: temp,
appTemp: appTemp
});
}
});
}
});
});
and use them in your ejs file:
<p><%= temp %></p>
<p><%= appTemp %></p>
If you use something like express-session you can store your data in req.session object, and then use it in your file
If you don't need to have persistency across user session, you can store data in res.locals, which are recognized by most express view engines, for example EJS:
res.locals.temp = temp;
res.render('temp');
temp.ejs:
<% if (temp) { %>
<h2><%= temp %></h2>
<% } %>