John Skiles Skinner's portfolio

XMLHttpRequest blocked by CORS policy in local HTML document

My simple fix for this error: Access to XMLHttpRequest at 'https://example.com/api/endpoint?format=raw' from origin 'null' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'file://' that is not equal to the supplied origin.

Recently while building a proof-of-concept for a snippet of JavaScript that was provided by a software vendor I encountered this CORS error.

Access to XMLHttpRequest at 'https://example.com/api/endpoint?format=raw' from origin 'null' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'file://' that is not equal to the supplied origin.

I habitually write HTML documents in a local text file, viewing them by dragging the file icon into my web browser window. This displays the webpage without any web server. In this case, the webpage contained a request for an external script that evidently violates the browser's same-origin policy. I think the reason for this is that file:// is not the expected protocol scheme.

An error message reading: Access to XMLHttpRequest at 'https://example.com/api/endpoint?format=raw' from origin 'null' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'file://' that is not equal to the supplied origin.
An example of the error message in Chrome browser's developer tools

I spent a while investigating how to set the Access-Control-Allow-Origin for a local file. Without a web server, just opening HTML documents locally, it is tricky to convince the browser that a web server is setting a header. There is a Chrome plugin (which I didn't try) that claims to do this, the Moesif Origin & CORS Changer.

The fastest solution for me was to run a local web server. I didn't want to install anything new, but because I have Python installed, I already had a web server. I ran this command from the directory with my HTML document:

python3 -m http.server

Then I visited http://localhost:8000/ and was able to view the files in the directory. Clicking on my HTML file, the page displayed free of CORS errors, and the JS snippet executed.

If you don't have Python, you can learn how to install it here.


Top of page | Blog index | Return home