如何使用无服务器功能和 axios 将开放天气 API 数据传递给 React 前端

How to pass open weather API data to React front-end with serverless function and axios

我目前正在尝试在无服务器函数中调用 openweather API,将响应传递到 'return',然后使用 Axios 获取响应并设置我的组件状态与响应。

但是,每次它调用 JSON 都不会在响应中发送。相反,它只是 URL。然后状态更新为 URL 不出所料。

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

serverless 函数显然是错误的。但是我需要将我的无服务器函数更改为 return 数据,而不仅仅是 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 here 的 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);
  };