javascripthtmljsonr-markdownprepros

"Not allowed to load local resource" error when knitting to HTML document and running on a server


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.


Solution

  • 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.");
        });
    });