如何通过无服务器功能和axios将开放天气API数据传递到React前端



我目前正试图在无服务器函数中调用openweatherAPI,将响应传递到"return"中,然后用Axios获取响应,并用响应设置组件状态。

但是,每次它调用JSON时,都不会在响应中发送。相反,它只是URL。然后,状态被更新为URL,这不足为奇。

当我在Postman中调用API时,它会返回数据。所以我不明白我做错了什么。

无服务器功能显然是错误的。但是,我需要对无服务器函数进行哪些更改才能返回数据,而不仅仅是URL

功能如下:

module.exports = (req, res) => {
const url = `https://api.openweathermap.org/data/2.5/weather?q=London&appid=${process.env.OPEN_WEATHER_API}`;
const weatherResponse = url;
return res.status(200).json(weatherResponse);
};

然后我的Axios调用我的组件,调用无服务器功能:

this.state = {
weather: []
}
axios.get("/api/getCurrentWeather")
.then((response) => {
this.setState({
weather: response.data
})
console.log(this.state.weather)
})
.catch((error) => {
console.log(error)
})
}

任何建议都将不胜感激!

从客户端调用无服务器功能/api/getCurrentWeather

现在,在您的无服务器函数中,您必须在此处使用http的axios调用openweather api然后将错误或成功数据发送给您的客户端。

import axios from 'axios';
module.exports = async (req, res) => {
const url = `https://api.openweathermap.org/data/2.5/weather?q=London&appid=${process.env.OPEN_WEATHER_API}`;
const weatherResponse = await axios.get(url);
return res.status(200).json(weatherResponse.data);
};

最新更新