Dhanya
Dhanya

Reputation: 579

Local json file is not loading using ajax in react js

I have the following react component.

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;

when I try to load the local json file "data.json", it is showing a not found error. Do I need to pass any other parameters? My local json file resides in the same folder as that of GraphView.

Upvotes: 1

Views: 1448

Answers (1)

arve0
arve0

Reputation: 3647

Loading JSON from filesystem is turned off in most browsers, because security. This is normally called "cross origin", but Chrome also turns this off even when the origin (the HTML) is on the filesystem.

Just imagine how reading from the filesystem could impose security concerns. Should HTML from the filesystem be able to talk "cross-origin" with the internet?

Consider this HTML:

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

Which file should be allowed to load? evil.js or secret.txt? Worst case scenario, /etc/shadow is readable by the user running the browser.

You can turn off security feature in chrome by starting with the switch --allow-file-access-from-files, bad idea, but nice for debugging purposes.

A simple workaround is to start a web server.

  • In node: npm install -g node-static && static
  • In python 3: python -m http.server 8888, then open localhost:8888.

Upvotes: 1

Related Questions