Passing LON and LAT while using AXIOS to handle multiple API requests

31 Views Asked by At

I have an ok understanding at using node and axios to make api requests. The only issue I'm having right now is that I've retrieved the city name a user types and I'm trying to pass lon and lat based on the city name, from the open weather map's geo location api into a second request, open weather api, to get weather information. Lon and lat cannot be accessed before initialized. I've made a request using just node.js modules successfully but when I tried to pass lat and lon I still have the same issue.

This is my code so far:

app.post("/weather", async(req, res) => {
      try {
        const city = req.body.city;

        function getGeolocation() {
          return axios.get(GEO_URL, {
            params: {
              q: city,
              //limit: 1,
              appid: myAPIKey,
            },
          })
        };

        function getWeather() {
          return axios.get(API_URL, {
            params: {
              lat: `${longitude}`,
              lon: `${latitude}`,
              units: 'metric',
              appid: myAPIKey,
            },
          })
        };

        const [acct, perm] = await Promise.all([getGeolocation(), getWeather()]);

        const geolocationArray = JSON.parse(acct.data);
        let latitude = geolocationArray[0].lat;
        let longitude = geolocationArray[0].lon;

        //**CURRENT ERROR MESSAGE: on page Failed to fetch activity. Please try again.
        //in console Failed to parse response: Request failed with status code 400 
        //Failed to parse response: Cannot access 'longitude' before initialization

        const result = JSON.stringify(perm.data);

        console.log(JSON.stringify(perm.data.current.sunrise));
        let sunrise = result.current.sunrise;

        res.render("weather.ejs", {
          sunUp: sunrise,
          lon: longitude,
          lan: latitude
        });
0

There are 0 best solutions below