※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