0

I'm trying to load a local JSON file in an RMarkdown (knitting to HMTL):

```{js}

  $(document).ready(function(){
        $.getJSON("C:/Users/Data/my_json.json", function(data){
            console.log(data); 
        }).fail(function(){
            console.log("An error has occurred.");
        });
    });

```

So, I'm aware that I can't serve local files on chrome without running a server. So, I dropped the HMTL output from the RMarkdown into Prepros, which comes with a built-in HTTP & HTTPS server. It's running at http://localhost:8848/ And still I get the errors:

Not allowed to load local resource 

and

Failed to load resource: the server responded with a status of 404 (Not Found)

How can I fix this? I assumed I could run local JSON files via Prepros, since it's spinning up a server.

halfer
  • 19,824
  • 17
  • 99
  • 186
DiamondJoe12
  • 1,879
  • 7
  • 33
  • 81

1 Answers1

4

The browser wont let you load a file from the host - that would be a huge security issue.

You need to make it so that the server has an endpoint that returns the JSON, and then put in the url for your getJSON call, e.g.:

$(document).ready(function(){
    $.getJSON("http://localhost:8848/path/to/my_json.json", function(data){
        console.log(data); 
    }).fail(function(){
        console.log("An error has occurred.");
    });
});
dave
  • 62,300
  • 5
  • 72
  • 93
  • Dude! That worked. Thanks so much! If it's not too much trouble, can you explain what's going on conceptually here? I don't really understanding what's happening with the localhost and pointing to an "endpoint". Thanks in advance! – DiamondJoe12 Sep 22 '22 at 19:21
  • 2
    Conceptually it's just basic browser security - the browser won't let a website just load a random file from the host. If it did, any website you visit could do, e.g. ` $.getJSON("%LocalAppData%\Google\Chrome\User Data\Default\cookies")`, which would load your cookies for all websites from the filesystem, then they could use your cookies to e.g. login to your bank. By running a server, you are now running software which you control what it does - if you say "load this file", it lets you. So you give access to the browser by having a "web page" which gives you the data – dave Sep 22 '22 at 19:27