I'm creating a simple web app that fetches data asynchronously from three web apis. One is for location, one for weather and one for stock images. My files are as follow:
Index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Weather Journal</title>
</head>
<body>
<div id="app">
<div >
Weather Journal App
</div>
<form id="userInfo">
<div >
<label for="city">Enter City here</label>
<input type="text" id="city" placeholder="enter city here" required>
</div>
<div >
<label for="date">Enter departure date</label>
<input type="datetime-local" id="date" required>
<button id="submitBtn" type="submit"> Generate </button>
</div>
</form>
<div >
<div >Details</div>
<div>
<img id="city-pic" src="" alt="your city">
</div>
<div id="entryHolder">
<div><b>Temperature for next 16 days:</b></div>
<ul id="entries">
<div id="temp"></div>
<div id="time"></div>
</ul>
</div>
</div>
</div>
<script src="app.js" type="text/javascript"></script>
</body>
</html>
app.js:
const present = new Date();
const submitBtn = document.getElementById("submitBtn");
submitBtn.addEventListener("click", (e) => {
e.preventDefault();
const city = document.getElementById("city").value;
const departure = document.getElementById("date").value;
const [depart_date, depart_time] = departure.split("T")
const [depart_year, depart_month, depart_day] = depart_date.split("-")
const [depart_hour, depart_minute] = depart_time.split(":")
const future = new Date(depart_year, depart_month - 1, depart_day, depart_hour, depart_minute);
if (city !== "" || departTime !== "" || future < present) {
document.getElementById("time").innerHTML = `Departure in ${Math.ceil((future - present) / 3600000 / 24)} days`
getCity(geoURL, city, geoUsername)
.then(function (data) {
return getWeather(weatherURL, weatherKey, data["geonames"][0]['lat'], data["geonames"][0]['lng'])
}).then(weatherData => {
return postWeatherData("/addWeather", { temp: weatherData['data'][i]['temp'], datetime: weatherData['data'][i]['datetime'] })
}).then(function () {
return receiveWeatherData()
}).catch(function (error) {
console.log(error);
alert("Please enter a valid city and a valid time");
})
getPictures(city, pixabayURL, pixabayKey)
.then(function (picsData) {
const total = picsData['hits'].length
const picIndex = Math.floor(Math.random() * total)
return postPictureData("/addPicture", { pic: picsData['hits'][picIndex]["webformatURL"] })
})
.then(function () {
return receivePictureData()
}).catch(function (error) {
console.log(error);
alert("No pictures found")
})
}
})
const getCity = async (geoURL, city, geoUsername) => {
const res = await fetch(`${geoURL}q=${city}&username=${geoUsername}`);
try {
const cityData = await res.json();
return cityData;
}
catch (error) {
console.log("error", error);
}
}
const postWeatherData = async (url = "", data = {}) => {
const response = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
temp: data.temp,
datetime: data.datetime
})
});
try {
const newData = await response.json();
console.log(newData)
return newData;
}
catch (error) {
console.log(error);
}
}
const receiveWeatherData = async () => {
const request = await fetch("/allWeather");
try {
const allData = await request.json()
const node = document.createElement("li");
const textnode = document.createTextNode("DATE: " allData['datetime'] "\t" "TEMPERATURE: " allData['temp']);
node.appendChild(textnode);
document.getElementById("entries").appendChild(node);
}
catch (error) {
console.log("error", error)
}
}
const getWeather = async (weatherURL, weatherKey, lat, lon) => {
const res = await fetch(`${weatherURL}&lat=${lat}&lon=${lon}&key=${weatherKey}`);
try {
const weatherData = await res.json();
return weatherData;
}
catch (error) {
console.log("error", error);
}
}
const getPictures = async (city, pixabayURL, pixabayKey) => {
const query = city.split(" ").join(" ");
const res = await fetch(`${pixabayURL}key=${pixabayKey}&q=${query}`);
try {
const picsData = await res.json();
return picsData;
}
catch (error) {
console.log("error", error)
}
}
const receivePictureData = async () => {
const request = await fetch("/allPictures");
try {
const allData = await request.json()
document.getElementById("city-pic").src = allData['pic'];
}
catch (error) {
console.log("error", error)
}
}
const postPictureData = async (url = "", data = {}) => {
const response = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
pic: data.pic
})
});
try {
const newData = await response.json();
return newData;
}
catch (error) {
console.log(error);
}
}
server.js:
// Setup empty JS object to act as endpoint for all routes
cityData = {};
weatherData = {};
picturesData = {};
// Require Express to run server and routes
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
// Start up an instance of app
const app = express();
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
app.use(cors())
// Initialize the main project folder
app.use(express.static('dist'));
app.use(express.static('website'));
app.get("/all", function sendData(req, res) {
res.send(cityData);
})
app.get("/allWeather", function sendWeather(req, res) {
res.send(weatherData);
})
app.get("/allPictures", function sendPictures(req, res) {
res.send(picturesData);
})
app.post("/addWeather", (req, res) => {
weatherData['temp'] = req.body.temp;
weatherData['datetime'] = req.body.datetime;
res.send(weatherData);
})
app.post("/addPicture", (req, res) => {
picturesData['pic'] = req.body.pic;
res.send(picturesData);
})
// Setup Server
app.listen(3000, () => {
console.log("App listening on port 3000")
console.log("Go to http://localhost:3000")
})
The server uses node, express, cors, and body-parser as the tools to create it.
I have not included the api keys or usernames. Right now I need to loop over the weather data that is return from the api (which fetches 16 days of data). The code :
.then(weatherData => {
return postWeatherData("/addWeather", { temp: weatherData['data'][i]['temp'], datetime: weatherData['data'][i]['datetime'] })
should use the 'i' variable to loop over all the possible 16 entries for a certain location. Right now if run the app with 0 in place of 'i' it just gives the temperature for the next day. I want to get the weather data for 16 days and append it to the html 'ul' that I have in the document. Can someone guide me. This is the last step in the project that I need to complete by 10 november!
CodePudding user response:
A series of promises can be created using Array.map()
over received weather data, and a series of promises can be resolved using Promise.all()
. The returned output would be an array of received temperature information. Please see the below code
(PromiseLikeObject)
.then(weatherData => {
const promiseCollection = weatherData['data'].map(d => postWeatherData("/addWeather", { temp: d.temp, datetime: d.datetime }));
return Promise.all(promiseCollection);
});
CodePudding user response:
If I understood you right, I think you could just map over the data and display it in DOM, just adjust the to the array you receive.
const postWeatherData = async (url = "", data = {}) => {
const response = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
temp: data.temp,
datetime: data.datetime
})
});
try {
const newData = await response.json();
let entryHolder = document.getElementById("entryHolder");
const weather = newData.map((data, index) => {
return `<ul id="entries">
<div id="temp">${data.temp}</div>
<div id="time">${data.time}</div>
</ul>`
}).join('')
entryHolder.innerHTML = weather
}
catch (error) {
console.log(error);
}
}