如何访问使用 create react app 创建的 src 文件夹中的 json 文件 [英] How to access json file in src folder created using create react app

查看:48
本文介绍了如何访问使用 create react app 创建的 src 文件夹中的 json 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm a newbie to react. I have created react application using npx create-react-app. In actions,axios.get is throwing localhost:3000 file not found error. Below is the code which is in 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

This is the project structure [1]: https://i.stack.imgur.com/CwTJg.png

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

What am I doing wrong? I couldn't find a proper solution for this. Thanks in advance.

推荐答案

我同意 Easwar 的观点,你需要看看那个问题的答案.

I agree with Easwar, you need to look at the answer to that question.

似乎 axios 仅在/public 文件夹中运行,因此您需要 public 文件夹中的 json 文件.如果需要,您可以将它们放在公共文件夹中的文件夹中.

It appears axios only operates in the /public folder so you would need your json files in the public folder. You could put them within a folder in the public folder if you wanted.

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

This makes sense because the webpack bundle is in the public folder and once the app is bundled only files within the public folder are available to your react project.

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

Since axios is an xhr request library at the moment you use it the only file structure it can possibly see is in the public folder so most likely: index.html, manifest.json, and your webpack bundle.js which has all your js code bundled into 1 file.

这篇关于如何访问使用 create react app 创建的 src 文件夹中的 json 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆