JSON Javascript external file

Asked

Viewed 519 times

0

I would like to upload an external json file to my html page through javascript.

When I tried, the following error occurred: " Cross origin requests are only supported for Protocol schemes: http, data, Chrome, Chrome-Extension, https".

It accuses that I cannot upload files using "File://c:/", but I want my file to be next to the folder on my machine.

One solution I found was to put all my code and run it for example by wampserver using localhost:80, but I wouldn’t want you to have to install wamp or something like that.

It is possible to upload the data from the json file without having to use this solution?

  • It would be good to add to the question the code you are using.

2 answers

1

"Cross origin requests" is the key term here.

With that file://c: there, you are trying to upload something from your user’s file system. If this would work, your page could actively access the disk files of whoever entered your page.

This would be more or less equivalent to having the password of everyone’s cell phone that enters your physical store.

Put JSON in the same folder as your web application and load how you would load any CSS or Javascript. So the browser knows that you want to access something that is yours and not the user’s.

Example of how to load a JSON like this. Have a Javascript file called foo.js:

var meuJson = JSON.stringify({pessoa: { idade: 30, nome: "fulano" }});
function obterJson() { return meuJson; }

And to consume on your page:

<script type="text/javascript">
    var json = obterJson();
</script>

Now, if you want to access as if it were the JSON return of a service (i.e.: using ajax), there is no way. You will need an HTTP server to serve this JSON anyway.

0

You need to use HTTP protocol, there is no other way, but not to install Wamp, you may have Node installed on your machine and install the package http-server. this will provide you with an HTTP protocol without using Wamp Remember, http-server will do something similar to wamp.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.