简体   繁体   English

尝试在 React App 中“获取”json 时找不到文件错误

[英]File not found error when trying to 'fetch' json in React App

Am trying to read a Json file in my react app, but console shows that the url for my json file is 404. Can any one please look into what is wrong in my code我试图在我的反应应用程序中读取一个 Json 文件,但控制台显示我的 json 文件的 url 是 404。任何人都可以看看我的代码有什么问题

Below is the error shown in browser console.以下是浏览器控制台中显示的错误。 When I open the json url that is shown in network tab, it redirects to the page instead of showing json -当我打开网络选项卡中显示的 json url 时,它重定向到页面而不是显示 json -

在此处输入图片说明

Below is my code -下面是我的代码 -

- ——

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;

My Json is as below -我的 Json 如下 -

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

Since JSON file is already inside the react application you can import it directly. 由于JSON文件已经在react应用程序中,因此您可以直接导入它。 you can use fetch to get JSON/XML responses from other servers/API 您可以使用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;

I faced this situation today.我今天遇到了这种情况。 Got to know what was happening.才知道是怎么回事。 It seems the app is looking for the JSON file at the root level or inside the public folder present at the root level.该应用程序似乎正在根级别或存在于根级别的公用文件夹中查找 JSON 文件。
And if someone still looking for a solution related to the usage of local JSON (mimicking server calls) then make sure you put the JSON at the root level of your project.如果有人仍在寻找与使用本地 JSON(模仿服务器调用)相关的解决方案,请确保将 JSON 放在项目的根级别。 So there could be two scenarios I can think of -所以我能想到的可能有两种情况——

  1. If you have a public folder at root level --> I am taking the above scenario mentioned in the question.如果你有一个public的根级别的文件夹- >我走在问题中提到了上述场景。 Your JSON should be present inside /public/json/results.json您的 JSON 应该存在于/public/json/results.json
  2. If you don't have a public folder --> Put the JSON file at the root level same as your src .如果您没有public文件夹 --> 将 JSON 文件放在与src相同的根级别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试通过提取读取json文件时出现错误 - Getting an error when trying to read json file via fetch 尝试获取时的主干JSON错误 - Backbone JSON error when trying to fetch React App 获取 json 数据时出错? - React App to fetch json data getting an error? 尝试从 django 应用程序打开 json 文件时出现编码错误 - Encoding error when trying to open json file from django app 未找到资产的文件或变体:尝试加载 JSON 凭据时出现 assets/credentials.json 错误 - No file or variants found for asset: assets/credentials.json error when trying to load in JSON credentials 尝试从GitHub存储库中获取一些JSON文件时无法加载错误 - Failed to load error when trying to fetch some JSON file from GitHub repo JSON 解析错误:使用 fetch 向后端发送请求时,React Native App 上出现意外的标识符“隧道” - JSON Parse error: Unexpected identifier “Tunnel” on React Native App when using fetch to send request to backend JSON.h:尝试导入JSON框架时找不到文件 - JSON.h : File not found when trying to import the JSON framework 尝试使用 django 项目上的 AJAX 方法获取本地 JSON 文件时出现错误 404(未找到) - error 404 (Not Found) when trying to get local JSON file with AJAX method on django project 尝试使用输入数据发送ID时反应获取错误 - React fetch error when trying to send Id with input data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM