代码之家  ›  专栏  ›  技术社区  ›  Kevin

从公用文件夹中获取本地JSON文件

  •  24
  • Kevin  · 技术社区  · 8 年前

    这是我的项目结构:

    • 平民的

        • 马托。json(my.json文件)
    • src公司

      • 组件

        • 应用程序。js公司

    public 文件夹如果我在中使用文件构建项目 src 文件夹中,我的文件将包含在生成的 main.js 通过命令 yarn build .

    我想修改我的json文件,而不总是重建我的应用程序。

    import Data from './mato.json'
    

    或:

    export default { 'mydata' : 'content of mato.json'}
    import data from 'mydata';
    

    我试着去拿我的。json文件,但“文件方案”与 fetch() &铬。。

    (Chrome错误:–index.js:6获取API无法加载file:///D:/projects/data/mato.json.不支持URL方案“文件”。”)

    这是我的获取代码:

    fetch(`${process.env.PUBLIC_URL}/data/mato.json`)
    .then((r) => r.json())
    .then((data) =>{
        ReactDOM.render(<App appData={JSON.stringify(data)}/>, document.getElementById('root'));
    })
    

    它只适用于Firefox。我也试过了 mode: 'cors' 不会更好。

    当然,我没有任何服务器,这是一个本地项目,因此如果有人知道如何在本地读取JSON文件,我将不胜感激。

    5 回复  |  直到 8 年前
        1
  •  34
  •   Jason Roman    8 年前

    我认为你的论点是错误的。应该是这样的

    fetch('data/mato.json')
    
        2
  •  8
  •   Blessing    5 年前

    你还需要通过一些 headers 指示 Content-Type Accept application/json 告诉您的客户,您正试图从服务器访问和接受一些JSON资源。

      const getData=()=>{
        fetch('data/mato.json'
        ,{
          headers : { 
            'Content-Type': 'application/json',
            'Accept': 'application/json'
           }
        }
        )
          .then(function(response){
            console.log(response)
            return response.json();
          })
          .then(function(myJson) {
            console.log(myJson);
          });
      }
      useEffect(()=>{
        getData()
      },[])
    
        3
  •  5
  •   Lex Soft    7 年前

    因此,fetch('data/mato.json')就足够了。

        4
  •  0
  •   ashish kadali    4 年前

    给出公共文件夹中的JSON文件名,并存储数据链接

    componentDidMount() {
        fetch("./url.json")
          .then((res) => res.json())
          .then((data) => {
            this.setState({ links: data });
            console.log(this.state);
          });
      }
    
        5
  •  -2
  •   Hamid Alinia    5 年前

    为什么使用fetch?我觉得速度很慢。。。 我认为这个解决方案会更好。。。 您可以将此行添加到索引中。html:

    <script type="text/javascript" src="settings.js"></script>
    

    然后在设置中。js您可以这样做:

     window.globalTS= {
      "site_url": "hi.com",
      "home_url": "hello.com"
    };
    

    现在,在您的组件中,您可以获得如下变量:

    console.log(window.globalTS.site_url);