reactjs - 如何访问使用 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
我究竟做错了什么?我找不到合适的解决方案。提前致谢。
解决方案
我同意 Easwar,您需要查看该问题的答案。
看来 axios 仅在 /public 文件夹中运行,因此您需要将 json 文件放在 public 文件夹中。如果需要,您可以将它们放在公用文件夹中的文件夹中。
这是有道理的,因为 webpack 包位于 public 文件夹中,并且一旦应用程序被捆绑,只有 public 文件夹中的文件可用于您的 react 项目。
由于 axios 在您使用它时是一个 xhr 请求库,因此它可能看到的唯一文件结构是在公共文件夹中,所以很可能是:index.html、manifest.json 和您的 webpack bundle.js,其中包含您的所有 js 代码捆绑到 1 个文件中。
推荐阅读
- reactjs - React 和 Type 脚本 createContext 函数的初始数据
- python - Google Cloud App Engine 部署失败 (Django)
- javascript - 获取的对象未分配给 React 状态
- installation - Visual Studio 安装程序无法读取 x64 注册表
- c - 最简单的 C 运算符的问题
- r - 在两个数据集的 facet Wrapped ggplot 上查找多个峰值密度
- node.js - mapbox gl js 的 CSP,使用 dockerize nodejs 和 nginx 创建的应用程序
- javascript - 可插件或模块化的 reactjs
- javascript - 反应路由器dom的链接不起作用(找不到页面)
- python - 使用漂亮的汤从网页中的 url 抓取数据。Python