【问题标题】:File not found error when trying to 'fetch' json in React App尝试在 React App 中“获取”json 时找不到文件错误
【发布时间】:2019-07-02 08:54:19
【问题描述】:

我试图在我的反应应用程序中读取 Json 文件,但控制台显示我的 json 文件的 url 是 404。任何人都可以看看我的代码有什么问题

以下是浏览器控制台中显示的错误。当我打开网络选项卡中显示的 json url 时,它会重定向到页面而不是显示 json -

下面是我的代码-

-

import React from 'react';
import Header from './Header';
import Container from './Container'
import Footer from './Footer'

class App extends React.Component{

    constructor(props) {
        super(props);
        this.state = {
          error: null,
          isLoaded: false,
          products: []
        };
      }
    componentDidMount() {
        fetch("../json/results.json",{
            headers : { 
                'Content-Type': 'application/json',
                'Accept': 'application/json'
               }
        })
        .then(res => res.json())
          .then(
              console.log("--------"),
            (result) => {
              this.setState({
                isLoaded: true,
                products: result.Products
              });
            },
            // Note: it's important to handle errors here
            // instead of a catch() block so that we don't swallow
            // exceptions from actual bugs in components.
            (error) => {
              this.setState({
                isLoaded: true,
                error
              });
            }
          )
      }

    render(){
        const { error, isLoaded, products } = this.state;
        if (error) {
            return <div>Error: {error.message}</div>;
          } else if (!isLoaded) {
            return <div>Loading...</div>;
          } else {
                return(
                    <div>
                    <Header />
                    <br></br>
                    <Container />
                    <ul>
                        {(products || []).map(item => (
                            <li key={item.content_id}>
                            {item.content_id} {item.content_type}
                            </li>
                        ))}
                    </ul>
                    <br></br>
                    <Footer />
                    </div>
                );
            }
    }
}

export default App;

我的 Json 如下 -

{
    "Products": [
        {
        "content_id": "1211122910721",
        "content_type": "AVG_Product_C"
    ]
}

【问题讨论】:

  • 为什么需要使用fetch来加载本地json?您可以像从库中导入模块一样导入 json
  • @HemadriDasari 仍然是初学者,正在尝试学习 React。我不确定如何在我的 App.js 文件中导入和使用 JSON
  • 请分享您的应用组件的文件夹结构和Json文件。否则很难提供帮助
  • @HemadriDasari 这是我的文件夹结构 - ibb.co/pZxkBRv
  • 路径看起来绝对正确。您确定收到文件未找到错误吗?

标签: json reactjs fetch


【解决方案1】:

我今天遇到了这种情况。想知道发生了什么。该应用似乎正在根级别或根级别的公用文件夹中查找 JSON 文件。
如果有人仍在寻找与使用本地 JSON(模仿服务器调用)相关的解决方案,那么请确保将 JSON 放在项目的根级别。所以我可以想到两种情况-

  1. 如果您在根级别有一个public 文件夹--> 我正在考虑问题中提到的上述情况。您的 JSON 应该出现在 /public/json/results.json
  2. 如果您没有 public 文件夹 --> 将 JSON 文件放在与您的 src 相同的根级别。

【讨论】:

    【解决方案2】:

    由于 JSON 文件已经在 react 应用程序中,您可以直接导入它。您可以使用 fetch 从其他服务器/API 获取 JSON/XML 响应

    import React from "react";
    import Header from "./Header";
    import Container from "./Container";
    import Footer from "./Footer";
    import JSONResult from '../json/results.json';
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          products: JSONResult.Products || []
        };
      }
      render() {
        const { products } = this.state;
        return (
          <div>
            <Header />
            <br />
            <Container />
            <ul>
              {products.map(product => (
                <li key={product.content_id}>
                  {product.content_id} {product.content_type}
                </li>
              ))}
            </ul>
            <br />
            <Footer />
          </div>
        );
      }
    }
    
    export default App;
    

    【讨论】:

    • 即使在使用您的代码示例后也会遇到同样的错误
    • 它会生成一个错误通知:模块 '"/path/.../results"' 没有默认导出。在这种情况下,我在 "compilerOptions" 内部的 tsconfig.json 中添加了 "resolveJsonModule": true 并使用以下模式导入:import * as JSONResult from '../json/results.json'; 一切正常!
    猜你喜欢
    • 2021-06-08
    • 2021-09-08
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    相关资源
    最近更新 更多