【问题标题】:How to fetch API in Node.js and send to Reactjs ( youtube video included for more detail explain)如何在 Node.js 中获取 API 并发送到 Reactjs(包含 youtube 视频以获取更多详细说明)
【发布时间】:2021-10-12 11:33:16
【问题描述】:

感谢我的问题。

我目前正在尝试构建一个简单的天气应用程序,将 React 用于客户端Node.js 作为服务器端以获取天气 API

enter image description here

但我正在努力解决的主要问题将数据获取到客户端。 我尝试使用 Axios 和 useEffect 来获取数据。但我不知道该怎么做。

enter image description here

为了让您更好地理解我的问题,我制作了一个视频。

https://youtu.be/obzvTHEnd70

源代码在这里:https://github.com/good-practice00/node-weather-api

如果你能帮助我,我将不胜感激!谢谢!

【问题讨论】:

  • 视频和屏幕截图有助于将 React 组件的代码添加到问题中
  • 是的,请添加一个最小的可重现示例,说明您尝试过的内容以及尝试后会发生什么:stackoverflow.com/help/minimal-reproducible-example
  • @RameshReddy 非常感谢先生的帮助!!!按照你的建议,问题已经解决了!!!再次感谢您的时间和友好的回复!上帝保佑你!!!!!!

标签: javascript node.js reactjs api


【解决方案1】:

有多个问题:

使用type="button" 阻止表单提交

     <form>
        <input
          type="text"
          name="location"
          value={weather.location}
          placeholder="location"
          onChange={handleChange}
        />
        <button
          type="button"
          onClick={() => {
            handleSubmit(weather.location);
          }}
        >
          Search
        </button>
      </form>

fetchWeather 不必接受参数,因为您维护的是weather 状态,实际上是weather.location

const fetchWeather = async () => {
    const res = await fetch(`/weather/${weather.location}`);
    const data = await res.json();
    console.log(data);
    setWeatherInfo(data);
  };

不知道你为什么在挂载时调用fetchWeather

  useEffect(() => {
    fetchWeather();
  }, []);

正确的地方应该是:

const handleSubmit = () => {
    fetchWeather();
    // axios.post("/weather"); maybe you don't need this?
  };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    • 2019-09-14
    • 2014-11-20
    • 2014-04-20
    相关资源
    最近更新 更多