2015-11-27 60 views
0

我有以下反应组件。本地json文件未使用ajax在反应js中加载

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相同的文件夹中。

+3

你可能正在编译它到另一个文件夹中的其他文件? –

回答

0

从大多数浏览器中的文件系统加载JSON是关闭的,因为安全。这通常称为“交叉来源”,但即使原始文件(HTML)位于文件系统上,Chrome也会关闭此功能。

想象一下,如何从文件系统读取可能会引起安全问题。文件系统中的HTML应该能够与互联网“交叉来源”谈话吗?

考虑这个HTML:

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

哪一个文件应该被允许加载? evil.jssecret.txt?最差的情况下,运行浏览器的用户可以读取/etc/shadow

您可以通过从开关--allow-file-access-from-files开始,关闭Chrome中的安全功能,这个主意不好,但很适合用于调试目的。

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

  • 在节点:npm install -g node-static && static
  • 在Python 3:python -m http.server 8888,然后打开本地主机:8888。