34

I've started to write a HTML file which displays data with JavaScript. Since it shall be done as easy as possible I don't want to run nodejs oder any other local http server. I've just opened the HTML file in a browser (url is file:///home/visu/index.htm).

Everything is fine, till a jquery ajax request to a online API is done in the index.htm. The browser blocks the request with the message:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://x.x.x.x. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."

How can I get rid of the problem without starting a local http server?

A possible solution is to start the browser with some "no security flags" or disable CORS with plugins, but this I've to do manually all the time so I don't like it.

Freude
  • 819
  • 1
  • 10
  • 18
  • You can't get rid of the problem whether or not you start an HTTP server. The API you're accessing isn't meant to be used from a browser, so disabling the browser's security feature is the only way to make it work from a browser. Depending on your use case you should consider just running the script without a browser (use node.js, but no need to start a server). – Paul Jan 20 '18 at 23:27

6 Answers6

6

When your browser will perform an AJAX request to a different server than the one hosting the current page, it first sends an OPTIONS HTTP message. In that message it sends the following header:

origin: http://my-web-server.com

And the backend server will respond with:

access-control-allow-origin: http://my-web-server.com

But, when you don't have a webserver, there is no address for your browser to put in that origin header. That's why your browser disallows you to do any AJAX request from a local file (maybe you can disable the browser's CORS security as someone mentioned in the comments, but that can put you at risk of malicious sites).

Another option

You can tell your browser to allow to connect from localhost to a backend if you change your backend to return the following header:

access-control-allow-origin: https://localhost:8888

And, you also need to tell your localhost server to serve your page in HTTPS instead of HTTP. Once both conditions are met, CORS validations won't fail.

Notice that to enable HTTPS you'll need to have a SSL cert and key, you can generate them with the following command:

openssl req -x509 -out localhost.crt -keyout localhost.key \
  -newkey rsa:2048 -nodes -sha256 \
  -subj '/CN=localhost' -extensions EXT -config <( \
   printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth")

The source of that command and more information are found in this page from Let's Encrypt.

Daniel
  • 21,933
  • 14
  • 72
  • 101
5

Not Possible By Design

CORS are always blocked when attempted from a file on disk (web pages using the file:// protocol). There is nothing you can do to make it work from a file. It is simply impossible.

The reasoning for this is that files on disk have no real "origin" to allow the backend server to determine the validity of the request. You can have a file for an issue tracking html on the same disk as a file for a blog html. The server cannot know which html requested the data (you can even have someone else's file shared via Dropbox with embedded javascript that may attempt to access your server's data when you open it - nobody expects a hacking attempt when they simply open a plain html file!!).

This is why no browser vendor will allow you do make CORS requests from a file.

You Need a Server

To make it work you will need a HTTP server. There are lots of options for this from installing Apache/Nginx on your machine to running dev servers like webpack-dev-server or local-web-server. As long as the protocol is http:// or https:// you are allowed to make CORS requests.

Once you have a server serving your html file you can configure CORS on your backend as usual.

slebetman
  • 109,858
  • 19
  • 140
  • 171
2

On Firefox, you can install this addon: https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/ to disable CORS for the respective tab. Then, any request will also work on file:/// URIs. Be careful though!

Philipp Stephan
  • 372
  • 5
  • 17
  • 1
    Even with this addon, I still get (for a related issue): `Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///Users/bbarker/workspace/RustyRogue/wasm/rusty_rogue_bg.wasm. (Reason: CORS request not http).` – bbarker May 12 '23 at 15:08
0

Either mock Ajax calls, or start web server with reverse proxy and HTTP rewriting configured, since I'm sure you don't want, or have not access to configure API server CORS headers.

If you don't want to mock ajax calls, then use either:

  1. node-http-proxy
  2. nginx - if you don't have nodejs and you don't want to install it.
Milan Jaric
  • 5,556
  • 2
  • 26
  • 34
  • 4
    Hi, have you read the "without starting a local http server" in the OP question ? – TOPKAT Jun 16 '20 at 17:30
  • 1
    Yes I did! My answer still stands since CORS browser policy is applied even on `file://` protocol. And since you can not change HTTP headers "on you filesystem", then the only option is some kind of reverse proxy or webserver that should serve that file for you. – Milan Jaric Jun 17 '20 at 18:21
0

If you are importing your javascript file using the type module:

<script type="module" src="code.js"></script>

Remove the type module, like that:

<script src="code.js"></script>

If you aren't using the type module, and it is still giving CORS error, the solution is to copy and paste all the .js files into your html file. So, instead of using the loading the js file, open the tag and add the code inside it, to your .html file. Example:

<html>
<head>
    <script>
        // Place your js code here. Just the code, not the file path.
        // Many files can be placed here.
    </script>
</head>
</html>

Obs: The best solution is still to create a local server, but this is a work around solution.

Derzu
  • 7,011
  • 3
  • 57
  • 60
-4

If you can not set it up access-control-allow-origin, you can try this.

Use "callback" function if your data is not in same domain. And wrap your data "jsonCallback(" ... data ... ") as my example: http://www.ceducation.cz/akce-plnytext.json?short=1&callback=?

function jsonCallback(json) {
  $.each(json, function(key, val) {
    // your data is here
    console.log('date: ' + val.date);
    console.log('address: ' + val.address);
    console.log('---');
  });
}

$(document).ready(function() {

  $.getJSON("http://www.ceducation.cz/akce-plnytext.json?short=1&callback=?", function(data) {

  });

});

Working example