首页 > 解决方案 > 如何访问使用 create react app 创建的 src 文件夹中的 json 文件

问题描述

我是新手反应。我已经使用 npx create-react-app 创建了反应应用程序。在操作中,axios.get 抛出 localhost:3000 file not found 错误。下面是 src/actions/index.js 中的代码

       export function lang(language) {
      let url = "./../resources/strings/strings_" + language + ".json";
      return dispatch => {
        axios.get(url).then(response => {
          console.log(response.data)
        }).catch(response => {
          console.log(response);
        });
      }
    }

这是项目结构[1]:https ://i.stack.imgur.com/CwTJg.png

我究竟做错了什么?我找不到合适的解决方案。提前致谢。

标签: reactjsreduxreact-reduxaxios

解决方案


我同意 Easwar,您需要查看该问题的答案。

看来 axios 仅在 /public 文件夹中运行,因此您需要将 json 文件放在 public 文件夹中。如果需要,您可以将它们放在公用文件夹中的文件夹中。

这是有道理的,因为 webpack 包位于 public 文件夹中,并且一旦应用程序被捆绑,只有 public 文件夹中的文件可用于您的 react 项目。

由于 axios 在您使用它时是一个 xhr 请求库,因此它可能看到的唯一文件结构是在公共文件夹中,所以很可能是:index.html、manifest.json 和您的 webpack bundle.js,其中包含您的所有 js 代码捆绑到 1 个文件中。


推荐阅读