※在发布问题后编辑了一些代码。下面是新代码。
我正在尝试使用Netlify函数来隐藏我的API密钥来获取数据。但是,它返回一个304,并且似乎不起作用。下面的代码返回错误"SyntaxError: Unexpected < in JSON at position 0“,响应代码为304。
有人能帮我改进一下吗?
函数/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"
}发布于 2021-09-13 06:32:11
在您的netlify函数中,发出请求后,您需要使用.json来获取json数据
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API}`
);
const data = await response.json();https://stackoverflow.com/questions/69158145
复制相似问题