※发布问题后编辑了一些代码。新代码如下。
我正在尝试使用 Netlify 函数来隐藏我的 API 密钥以获取数据。但是,它返回 304 并且似乎无法正常工作。下面的代码返回错误“SyntaxError: Unexpected token < in JSON at position 0”,响应代码为 304。
任何人都可以帮助我如何改善这一点吗?
■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(运行“npm i netlify-cli --save-dev”)
"devDependencies": {
"netlify-cli": "^6.8.12"
}