简体   繁体   中英

Making API Calls

Am trying to make api calls to three apis and my code is as follows in my server. I get lat and lon from geoNames api call and used that lat and lon to get weather data from weatherbit, but it gives the error that is at the bottom of this post:

    const { date, city } = req.body;
  // Call to the geonames API
    const geoNames = `http://api.geonames.org/searchJSON? 
    q=${city}&maxRows=1&username=${process.env.USERNAME}`;
    console.log(`${process.env.USERNAME}`)
    fetch(geoNames)
    .then((res) => res.json())
    .then((json) => {
      // getting latitude and longitude
      const lat = json.geonames[0].lat;
      const lng = json.geonames[0].lng;
      console.log(geoNames)
      console.log(lat)
      console.log(lng)

      // Call to the weatherbit API
      const weatherBit = 
      `https://api.weatherbit.io/v2.0/forecast/daily?l 
lat=${lat}&lon=${lng}&key=${process.env.WEATHERKEY},${date}`;
      console.log(`${process.env.WEATHERKEY}`)
      fetch(weatherBit)
        .then((res) => res.json())
        .then((json) => { 
            console.log(json);
          const city = res.json.data[0].city_name;
          const icon = res.json.data[0].weather.icon;
          const description = res.json.data[0].weather.description;
          const tempHigh = res.json.data[0].max_temp;
          const tempLow = res.json.data[0].min_temp;
            
          // Call to the pixabay API
          const pixaBay = `https://pixabay.com/api/?key=${process.env.PIXAKEY}&q=${city}&image_type=photo`;
          fetch(pixaBay)
            .then((res) => res.json())
            .then((json) => {
                console.log(json)
              const img = json.hits[0].webformatURL;
              const pixObj = { city: city, icon: icon, description: description, tempHigh: tempHigh, tempLow: tempLow, img: img };
              res.send(pixObj);
              console.log(pixObj)
            });
        });
    });
});

I get the following errors when I run the code:

http://api.geonames.org/searchJSON?q=Cancun&maxRows=1&username=kamara.moses 21.17429 -86.84656 cda6df51d9a24b8c9d54b830f4eadb51 { error: 'API key not valid, or not yet activated.' } (node:69146) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined

Have you checked if your API-Key is valid? Or perhaps if you wrote a letter wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM