Recently, I have downloaded a HTML project from GitHub. Unfortunately, I could not open the index.html file in browser which showed empty content. The browser console was showing an error “Access to script at ‘file:///…’ from origin ‘null’ has been blocked by CORS policy”. If you are facing the situation, here is how to create a local server in Visual Studio Code to fix the issue and load the HTML file without error.
CORS Policy for File Protocol
<script type="module" src="/src/index.tsx"></script>
You may find the code something like above or with crossorigin attribute like below:
<script type="module" crossorigin src="file_path"></script>
The solution here is you need a local server to run the HTML file so that it works through HTTP and fixes the error.
Installing Live Server Extension in Visual Studio Code
Visual Studio Code is the super easy way to work with development projects and edit the files. The app is available both on Windows and Mac along with hundreds of free extensions. If you are not using Visual Studio Code, go to the official website and download the correct version for Mac or Windows.
Install and open the app and click the “Extensions” icon showing in the left sidebar (last icon from the top). Type “live server” and find Live Server extension from Ritwick Dey. This is a very popular extension with almost 39 million installations and click on “Install” button.
You will be prompted with a pop-up asking whether you trust the author. Click on “Trust Workspace & Install” button to proceed further.
After successful installation, you will see the extension’s details.
Open HTML File and Launch Server
Go to “File > Open” menu and select your project folder and you will see the tree view of all files/folders in the app. Find and select the HTML file in the folder which was showing CORS error. Click on the “Go Live” option showing in the bottom status bar.
You will see a message showing “Server is Started at port: 5500” with “source: Live Server (Extension)”.
Check Your Page and Edit Live
The good part with Live Server extension is that you can edit the content live. Simply change any content in your HTML file and save it. You will see the page is automatically reloaded in browser and shows the updated content. You can arrange the Visual Studio Code and browser apps side by side to quickly troubleshoot the page with live result.
Closing Local Server
When the local server is running, Visual Studio Code app will show “Port: 5500” at the bottom right corner. After finishing your work, click on the “Port: 5500” option.
This will stop / close the local server and you will see a message showing “Server is now offline”.
This is an easy way to fix “Access to script at ‘file:///…’ from origin ‘null’ has been blocked by CORS policy” error without installing NPM or any other complicated local server environment. If you are doing this for one-time purpose, then uninstall the extension after finishing the work.