Problem:
While trying to access a local file in html using:
xmlhttp.open(“GET”, “test.xml”, true)
We get CORS error,
Access to XMLHttpRequest at ‘file:///D:/test.xml‘ from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https, isolated-app.

It is different from the other CORS error which says No ‘Access-Control-Allow-Origin’ header is present on the requested resource, which occurs when front-end app calls the server-api app and our browser intercepts that request and stops the client app from getting it.
But our error occurs when we are trying to access a local file using file://
Solution:
Solution is to use server to host your file first.
# Step 1: Set up Local server
If you do not have local server installed. Use this command to install the local server first (You need to have nodejs installed before running it):
npm install http-server -g
# Step 2: Run the html file on the local server
Now go to the file-location where you have kept your file (probably the index.html) and open CMD there, then run this command to get the server started:
http-server -p8000
if port 8000 would not be free then you may use another port like 8001, below CMD output is the probable output.
# Step 3: See the output
To see the output in browser:
Open browser and go to:
http://localhost:8000
Now you should be able to see the file running on the browser 🙂

More from Node/Javascript:




