本地json文件没有在react js中使用ajax加载

Local json file is not loading using ajax in react js

本文关键字:ajax 加载 js react 文件 json 本地      更新时间:2023-09-26

我有以下react组件。

import React, { Component } from 'react';
class GraphView extends Component { 
    constructor(props){
        super(props);       
        this.state = {      
            datajson: ''
        };      
    }   
    componentDidMount() {
        $.ajax({        
            url: 'data.json',
            dataType: 'json',           
            success: function(data) {
              this.setState({datajson: data});
            }.bind(this)
      });
    }
    render() {      
        return(     
            <div>   
                ...
            </div>
        );
    }
}
export default GraphView;

当我尝试加载本地json文件"data.json"时,它显示了一个未找到的错误。我需要传递任何其他参数吗?我的本地json文件与GraphView位于同一个文件夹中。

从文件系统加载JSON在大多数浏览器中都是关闭的,因为安全性。这通常被称为"跨原点",但Chrome也会关闭它,即使原点(HTML)在文件系统上。

想象一下,从文件系统读取可能会带来怎样的安全问题。文件系统中的HTML是否应该能够与互联网进行"跨源"通信?

考虑一下这个HTML:

<html>
  <head>
    <script src="http://ontheinternet.com/evil.js"></script>
    <script>
    $.ajax('/home/username/secret.txt', sendBackToMotherShip);
    </script>
  </head>
</html>

应该允许加载哪个文件?evil.js还是secret.txt?在最坏的情况下,运行浏览器的用户可以读取/etc/shadow

您可以从开关--allow-file-access-from-files开始关闭chrome中的安全功能,这是个坏主意,但对于调试来说很好。

一个简单的解决方法是启动web服务器。

  • 节点内:npm install -g node-static && static
  • 在python 3:python -m http.server 8888中,然后打开localhost:8888