0

※Edited some code after posting the question. New Code below.

I am trying to use Netlify Functions to hide my API key to fetch data. However, it returns a 304 and seems to be not working. The code below returns an error "SyntaxError: Unexpected token < in JSON at position 0" and the response code is 304.

Can anybody help me with how to improve this?

■functions/fetch-weather.js

const handler = async (event) => {
  try {
    const { city } = event.queryStringParameters;
    const API = process.env.REACT_APP_API_KEY;

    const response = await fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API}`
    );

    const data = await response.json();
    
    return {
      statusCode: 200,
      body: JSON.stringify(data),
    };
  } catch (error) {
    console.log({ statusCode: 500, body: error.toString() });
    return { statusCode: 500, body: error.toString() };
  }
};

module.exports = { handler };

■getCurrentWeather.js

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

    const response = await fetch(
      `/.netlify/functions/fetch-weather?city=${city}`
    );

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

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

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

■netlify.toml

[build]
    functions = "functions"
    publish = "src"

■package.json (ran "npm i netlify-cli --save-dev")

"devDependencies": {
    "netlify-cli": "^6.8.12"
  }

■console images (after opening page with "netlify dev") error network

user16589580
  • 103
  • 8

1 Answers1

0

In your netlify function after making a request you need to use .json to get the json data

const response = await fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API}`
    );

const data = await response.json();
Jack
  • 788
  • 3
  • 13
  • use console.log on your netlify function to print the error and attach it here It will be helpful – Jack Sep 13 '21 at 07:17
  • Thanks for your advice! I added error & network inspection images above. I also added several console.log but the only thing returned is "SyntaxError: Unexpected token < in JSON at position 0" – user16589580 Sep 13 '21 at 08:03
  • I was talking about that netlify function the code that runs on the netlify server see this docs https://docs.netlify.com/functions/logs/ try to see the logs of the function itself see what's going wrong inside the function – Jack Sep 13 '21 at 08:08