【问题标题】:Could not fetch local JSON file from public folder in React无法从 React 的公用文件夹中获取本地 JSON 文件
【发布时间】:2021-12-03 01:03:34
【问题描述】:

美好的一天,

我正在尝试从位于我的 react 应用程序的公共文件夹中的本地 JSON 文件中获取数据。我知道这是 SO 中的一个常见问题,并且我已经事先查找了与我的问题相关的主题,但下面是最近的一个。

Fetch local JSON file from public folder ReactJS

我正在使用下面的代码来获取我的 json 文件:

  const getResponse = () => {
    fetch('responseScript.json')
      .then(response => { response.json() })
      .then(data => { console.log(data) })

  }

  useEffect(() => {
    getResponse();
  })

主要问题是每当我从 json 文件中获取数据时,都会出现未定义和错误:

responseScript 位于公用文件夹中。我还检查了 devtools,在网络选项卡中,我可以看到请求状态代码是 200 OK。

我不确定它是否会增加问题,但我正在使用打字稿。我也研究过使用 FileStructure,但这似乎对我也不起作用。

编辑

我的 JSON 结构如下所示:

[
    {
     "Category":"Some text here",
     "Issue":"Some text here",
     "Answer":"Some text here",
     "Response":"Some text here"
    },
    {
     "Category":"Some text here",
     "Issue":"Some text here",
     "Answer":"Some text here",
     "Response":"Some text here"
    },
    {
     "Category":"Some text here",
     "Issue":"Some text here",
     "Answer":"Some text here",
     "Response":"Some text here"
    }

]

文件夹结构是

感谢任何帮助。谢谢!

【问题讨论】:

  • 似乎错误指向错误的 json,检查它实际返回的内容
  • 相对于 json 文件的位置,您的目录结构是什么样的?
  • 这表明您的“JSON”实际上是 HTML。
  • 应该是fetch(myRequest).then(response => response.json())你没有返回response.json
  • 附上项目的文件夹结构图。

标签: reactjs json typescript fetch-api


【解决方案1】:

使用这个:

  const getResponse = () => {
    fetch("./public/responseScript.json")
      .then(response => { response.json() })
      .then(data => { console.log(data) })

  }

【讨论】:

  • 我看到了同样的错误
  • 向我们展示未折叠的完整文件夹结构..
猜你喜欢
  • 2018-03-29
  • 1970-01-01
  • 2021-10-02
  • 2019-05-30
  • 1970-01-01
  • 1970-01-01
  • 2021-07-26
  • 2019-03-05
相关资源
最近更新 更多