Error when fetching API data using Netlify Functions

I have an error fetching data from an API using Netlify Functions. I have tried several times but always fail… I feel like I’m missing something so it would be great if somebody can help me. If this lacks information, please tell me!

■fetch-weather.js (/NetlifyFunctions)

exports.handler = async function(event, context) {
    try {
        const {city} = event.queryStringParameter;
        const API = process.env.REACT_APP_API_KEY;

        const url= `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API}`;

        const response = await fetch(url);
        const data = await response.json();
        console.log(data);
        return { 
            statusCode: 200,
            body: JSON.stringify({data})
        }
    } catch(err) {
        console.log(err);
        return { 
            statusCode: 400,
            body: JSON.stringify({error: 'Failed fetching data'})
        }
    }
}

■WeatherDisplay.js

const WeatherDisplay = () => {
  const [enteredCity, setEnteredCity] = useState('Tokyo');
  const weatherCtx = useContext(WeatherContext);
  const uiCtx = useContext(UIContext);

  const getCurrentWeather = async (city) => {
    const fetchWeather = async () => {
      uiCtx.setNotification({ status: 'pending', message: 'Loading...' });

      const response = await fetch(`/.netlify/functions/fetch-weather?city=${city}`, {headers: {
        'Content-type': 'application/json',
      }})

      if (!response.ok) {
        throw new Error('cannot get current weather data');
      }

      const data = await response.json();
      return data;
    };

    try {
      const data = await fetchWeather();
      weatherCtx.setLocation(data.name);
      const [array] = data.weather;
      weatherCtx.setWeather(array.main, array.description);
      uiCtx.setNotification({ status: 'success', message: 'Success' });
    } catch (error) {
      uiCtx.setNotification({ status: 'error', message: 'Cannot find result' });
    }
  };

  const inputChangeHandler = (e) => {
    setEnteredCity(e.target.value);
  };

  const submitSearchText = async (e) => {
    e.preventDefault();
    getCurrentWeather(enteredCity);
    setEnteredCity('');
  };
};

■netlify.toml

[functions]
  directory = "NetlifyFunctions"

■error

Could you share your site name?

Thank you! https://react-weather-app222.netlify.app/

As I can see, the function is working, however you seem to have an error in your code. This is from the function logs:

TypeError: Cannot destructure property 'city' of 'event.queryStringParameter' as it is undefined.
    at Runtime.exports.handler (/var/task/fetch-weather.js:3:16)
    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)

Checked here: Netlify App

Thank you for your quick response. Let me check if my understanding is right.

Here I fetch from a URL that includes city parameter const url= https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API};, and I can get it from const {city} = event.queryStringParameter; (const city = event.queryStringParameter.city)

Then I use this function to get the city parameter by adding ?city=${city}
const response = await fetch(/.netlify/functions/fetch-weather?city=${city}, {headers: {
‘Content-type’: ‘application/json’,
}})

When I search Paris in a search form and hit enter, the fetch URL includes paris so it looks it recognizes city… sorry I’m confused where the actual problem is.

I think it’s event.queryStringParameters (plural) and not event.queryStringParameter.

Yes it was plural… now it says “fetch is undefined” so I guess I need to import axios etc, otherwise I can’t use it like this?

Yes, fetch is not available in Node.js by default. You’d have to use node-fetch.

Thanks! I’m having npm issues, once I solve it I’ll post here how it went!

Now it’s responding with a 502…

■What I changed

  1. npm install node-fetch
  2. changed the code as below
import fetch from 'node-fetch';

const fetch = require("node-fetch");

exports.handler = async function(event, context) {
    try{
        const {city} = event.queryStringParameters;
       ........
}

■error

Hi @ayat1,

That’s probably not how you use node-fetch.

You either need to use require or import, but not both.

Thank you for responding. All of them below returns a 502.

  1. import fetch from ‘node-fetch’;
  2. const fetch = require(“node-fetch”); //502
  3. const fetch = request(‘node-fetch’).default; //502 (something I found here)
  4. const fetch = require(‘node-fetch’).default; //502

Below is the result of no.1
5:43:57 PM: 2021-09-15T08:43:57.249Z undefined ERROR Uncaught Exception {“errorType”:“Runtime.UserCodeSyntaxError”,“errorMessage”:“SyntaxError: Cannot use import statement outside a module”,“stack”:[“Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module”," at _loadUserApp (/var/runtime/UserFunction.js:98:13)“,” at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)“,” at Object. (/var/runtime/index.js:43:30)“,” at Module._compile (internal/modules/cjs/loader.js:999:30)“,” at Object.Module._extensions…js (internal/modules/cjs/loader.js:1027:10)“,” at Module.load (internal/modules/cjs/loader.js:863:32)“,” at Function.Module._load (internal/modules/cjs/loader.js:708:14)“,” at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)“,” at internal/main/run_main_module.js:17:47"]}
5:43:57 PM: 2021-09-15T08:43:57.459Z undefined ERROR Uncaught Exception {“errorType”:“Runtime.UserCodeSyntaxError”,“errorMessage”:“SyntaxError: Cannot use import statement outside a module”,“stack”:[“Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module”," at _loadUserApp (/var/runtime/UserFunction.js:98:13)“,” at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)“,” at Object. (/var/runtime/index.js:43:30)“,” at Module._compile (internal/modules/cjs/loader.js:999:30)“,” at Object.Module._extensions…js (internal/modules/cjs/loader.js:1027:10)“,” at Module.load (internal/modules/cjs/loader.js:863:32)“,” at Function.Module._load (internal/modules/cjs/loader.js:708:14)“,” at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)“,” at internal/main/run_main_module.js:17:47"]}
5:43:57 PM: 82760438 Duration: 165.20 ms Memory Usage: 14 MB 5:43:57 PM: Unknown application error occurred
Runtime.UserCodeSyntaxError
5:44:12 PM: 2021-09-15T08:44:12.723Z undefined ERROR Uncaught Exception {“errorType”:“Runtime.UserCodeSyntaxError”,“errorMessage”:“SyntaxError: Cannot use import statement outside a module”,“stack”:[“Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module”," at _loadUserApp (/var/runtime/UserFunction.js:98:13)“,” at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)“,” at Object. (/var/runtime/index.js:43:30)“,” at Module._compile (internal/modules/cjs/loader.js:999:30)“,” at Object.Module._extensions…js (internal/modules/cjs/loader.js:1027:10)“,” at Module.load (internal/modules/cjs/loader.js:863:32)“,” at Function.Module._load (internal/modules/cjs/loader.js:708:14)“,” at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)“,” at internal/main/run_main_module.js:17:47"]}
5:44:12 PM: dc514ce8 Duration: 179.60 ms Memory Usage: 14 MB 5:44:12 PM: Unknown application error occurred
Runtime.UserCodeSyntaxError
5:44:12 PM: 2021-09-15T08:44:12.984Z undefined ERROR Uncaught Exception {“errorType”:“Runtime.UserCodeSyntaxError”,“errorMessage”:“SyntaxError: Cannot use import statement outside a module”,“stack”:[“Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module”," at _loadUserApp (/var/runtime/UserFunction.js:98:13)“,” at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)“,” at Object. (/var/runtime/index.js:43:30)“,” at Module._compile (internal/modules/cjs/loader.js:999:30)“,” at Object.Module._extensions…js (internal/modules/cjs/loader.js:1027:10)“,” at Module.load (internal/modules/cjs/loader.js:863:32)“,” at Function.Module._load (internal/modules/cjs/loader.js:708:14)“,” at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)“,” at internal/main/run_main_module.js:17:47"]}
5:44:17 PM: 2021-09-15T08:44:17.902Z undefined ERROR Uncaught Exception {“errorType”:“Runtime.UserCodeSyntaxError”,“errorMessage”:“SyntaxError: Cannot use import statement outside a module”,“stack”:[“Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module”," at _loadUserApp (/var/runtime/UserFunction.js:98:13)“,” at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)“,” at Object. (/var/runtime/index.js:43:30)“,” at Module._compile (internal/modules/cjs/loader.js:999:30)“,” at Object.Module._extensions…js (internal/modules/cjs/loader.js:1027:10)“,” at Module.load (internal/modules/cjs/loader.js:863:32)“,” at Function.Module._load (internal/modules/cjs/loader.js:708:14)“,” at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)“,” at internal/main/run_main_module.js:17:47"]}
5:44:17 PM: c35379f7 Duration: 153.27 ms Memory Usage: 14 MB 5:44:17 PM: Unknown application error occurred
Runtime.UserCodeSyntaxError
5:44:18 PM: 2021-09-15T08:44:18.148Z undefined ERROR Uncaught Exception {“errorType”:“Runtime.UserCodeSyntaxError”,“errorMessage”:“SyntaxError: Cannot use import statement outside a module”,“stack”:[“Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module”," at _loadUserApp (/var/runtime/UserFunction.js:98:13)“,” at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)“,” at Object. (/var/runtime/index.js:43:30)“,” at Module._compile (internal/modules/cjs/loader.js:999:30)“,” at Object.Module._extensions…js (internal/modules/cjs/loader.js:1027:10)“,” at Module.load (internal/modules/cjs/loader.js:863:32)“,” at Function.Module._load (internal/modules/cjs/loader.js:708:14)“,” at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)“,” at internal/main/run_main_module.js:17:47"]}

Hi @ayat1,

Here’s a reference that works:

Thank you! I’ll check it out and try to work on improving my code!