I'm using geonames API and get data from it with a post request. Now I want to take part of these data (lat, long) and pass it through another API (weatherbit API) as my project need to pass (lat and long) in URL and get data from it
I try to make a get request in server-side to grab information and secure api key but it give me undefined
.
the code gives me undefined
in URL parameters
(EX. https://api.weatherbit.io/v2.0/forecast/daily/&lat=undefined&lon=undefined&key=API_KEY)
here my code How can I do this?
Edit: If I press the button again the request worked fine. So I have to press button 2 times before I get the lat and long data from first API. How to solve this>
in client-side
const getWeatherIoURL = async (url) => {
const response = await fetch(url);
try {
const data = await response.text();
//console.log(data);
return data;
} catch (error) {
console.error(error);
}
};
export default getWeatherIoURL;
my code in server-side for both post request and get request
weatherData = {}
app.post('/geoNamesData', (request, response) => {
weatherData['date'] = new Date();
weatherData['countryName'] = request.body.countryName;
weatherData['latitude'] = request.body.latitude;
weatherData['longitude'] = request.body.longitude;
response.send(weatherData);
});
//console.log(`your api is: ${process.env.API_WEATHER_KEY}`);
app.get('/weatherURL', (request, respond) => {
const url_forecast = 'https://api.weatherbit.io/v2.0/forecast/daily';
const lat = `lat=${weatherData.latitude}`;
const long = `lon=${weatherData.longitude}`;
const url = `${url_forecast}?${lat}&${long}&key=${process.env.API_WEATHER_KEY}`;
console.log(url);
respond.send(url);
});
my code structure
import geoNamesData from './geoNames_data';
import getWeatherIoURL from './weather_bit';
import postData from './post_geoNames';
//import exposeWeatherIoForecast from './weather_bit'
export function main() {
document.getElementById('search').addEventListener('click', (event) => {
event.preventDefault();
const baseURL = 'http://api.geonames.org/searchJSON?q=';
const API_Credentials = '&username=*********';
const destination = document.querySelector('#destination').value;
geoNamesData(baseURL, destination, API_Credentials).then((data) => {
//console.log(data);
postData('/geoNamesData', {
date: new Date(),
countryName: data.countryName,
latitude: data.lat,
longitude: data.lng,
});
});
getWeatherIoURL('/weatherURL').then((data) => {
console.log(data);
exposeWeatherIoForecast(data);
});
}
the flow of my code is get latitude, longitude and country name for specific city entered by user using geonames API then use the latitude and longitude from this request as a parameters in another API (wathearbit) - which need these data to complete the request - to get the current or forecast weather for the city and update UI with these information ** city, Country Name , weather **